Sie sind auf Seite 1von 800

Improvised wireless networking

By Anna Farahmand and Michael Webber


May 2012

Improvised wireless networking


Anna Farahmand and Michael Webber May 2012

"The spread of civilization may be likened to a fire; First, a feeble spark, next a flickering flame, then a mighty blaze, ever increasing in speed and power. Nikola tesla And today it is highly related to have a better communication systemAnna Farahmand

2012 Anna farahmand - Micheal Webber

Some part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means electronic, mechanical,photocopying, recording or otherwise without the prior written permission of the publisher. ---No legal action will be entered into regarding the copying printing or sharing of this document in its unaltered form so ...........please copy upload and share the wisdom of this document..................
No profiting from sales of this of this document will be tolerated. (Micheal Webber)

Find more from Anna Farahmand and Michael Webber by Google them or here: http://www.scribd.com/annafarahmand

Content
Prefeace An Introduction to Radio Physics What is a wave? Electromagnetic forces Polarization The electromagnetic spectrum Bandwidth Frequencies and channels Behavior of radio waves Absorption Reflection Diffraction Interference Line of sight Understanding the Fresnel zone Power Calculating with dB Network Design Networking 101 The OSI model The TCP/IP model The Internet protocols IP Addressing Subnets Global IP Addresses Static IP Addresses Dynamic IP Addresses Private IP addresses Routing Network Address Translation (NAT) Internet Protocol Suite Ethernet MAC addresses Hubs Switches Hubs vs. Switches Designing the physical network Point-to-point Point-to-multipoint Multipoint-to-multipoint 802.11 wireless networks Wireless mesh network IEEE 802.11s: Wireless mesh technology 14 18 18 19 21 21 20 23 23 22 25 26 28 29 30 31 31 33 33 35 37 38 38 39 41 42 42 42 43 46 47 48 48 48 49 49 52 53 53 54 55 57 61

Mesh networking with OLSR Using OLSR on Ethernet and multiple interfaces Link planning: Calculating the link budget Interactive design CGIs RadioMobile RadioMobile under Linux Avoiding noise Repeaters Traffic optimization Web caching Proxy server products Preventing users from bypassing the proxy server Firewall Two network cards Policy-based routing Mirroring a website Pre-populate the cache using wget Proxy specifications DNS caching and optimization Internet link optimization TCP/IP factors over a satellite connection Long round-trip time (RTT) Large bandwidth-delay product Transmission errors Performance-enhancing proxy (PEP) Antennas & Transmission Lines Cables Waveguides Connectors and adapters Antennas & radiation patterns Antenna term glossary -Input Impedance -Return loss -Bandwidth -Directivity and Gain -Radiation Pattern -Beamwidth -Sidelobes -Nulls -Polarization -Polarization Mismatch -Front-to-back ratio Types of Antennas 1/4 wavelength ground plane Yagi antenna Horn

67 74 83 89 90 90 91 92 94 95 95 96 97 98 98 98 99 100 101 103 104 104 105 105 106 107 107 109 110 113 113 113 113 114 114 115 117 118 118 118 119 119 120 121 121 122

Parabolic Dish BiQuad Reflector theory Amplifiers Practical antenna designs USB dongle as dish feed Collinear omni Cantenna NEC2 Networking Hardware Wired wireless Choosing wireless components Commercial vs. DIY solutions Professional lightning protection Building an access point from a PC Scenario 1: Masquerading access point Initial setup Setting up the interfaces Setting up masquerading in the kernel Setting up the DHCP server Adding extra security: Setting up a Firewall Scenario 2: Transparent Bridging access point Initial setup Setting up the Interfaces Starting the bridge Scenario 1 & 2 the easy way Wireless-friendly operating systems The Linksys WRT54G DD-WRT Security & Monitoring Physical security Switches Cables Power Water Masts Threats to the network Authentication Captive portals Popular hotspot projects Privacy SSL SSH OpenVPN Tor & Anonymizers Network Monitoring

123 123 125 125 126 127 127 134 139 140 140 142 143 145 147 148 148 149 149 150 151 152 152 152 154 154 155 156 157 158 158 159 159 159 160 160 160 162 165 167 167 168 170 172 173 175

An effective network monitoring example Monitoring the LAN (local traffic) Monitoring the WAN (external traffic) Detecting Network Outages Monitoring your network The dedicated monitoring server Where does the server fit in my network? What to monitor Wireless statistics Switch statistics Internet statistics System health statistics Types of monitoring tools Network detection Spot check tools Ping Traceroute and mtr Protocol analyzers Kismet KisMAC Tcpdump Wireshark Trending tools MRTG RRDtool Ntop Cacti NetFlow Flowc SmokePing EtherApe Iptraf Argus NeTraMet Throughput testing Ttcp Iperf Bing Realtime tools Snort Apache: mod_security Nagios Zabbix Ngrep Establishing a baseline Monitoring RAM and CPU usage

174 175 175 176 177 178 178 181 181 181 181 182 182 183 183 184 185 186 186 186 187 187 188 188 189 189 190 191 192 192 193 193 194 195 195 196 196 197 197 198 198 198 199 200 201 207

Solar Power Solar energy What about wind power? Photovoltaic system components The solar panel The battery The regulator The converter The load Putting it all together Solar Panel Parameters Panel parameters for system sizing Interconnection of panels How to choose a good panel Types of batteries Using car batteries States of charge Overcharge Overdischarge Battery Parameters Measuring the state of charge of the battery Battery and regulator protection Temperature effects Life expectancy versus number of cycles The power charge regulator DC/DC Converters DC/AC Converter or Inverter Wireless telecommunications equipment Selecting the voltage Wiring Orientation of the panels Azimuth Inclination How to size your photovoltaic system Data to collect Electrical characteristics of system components Required current in the worst month Number of panels Capacity of the battery or accumulator Building an Outdoor Node Waterproof enclosures Providing power Mounting considerations Guyed towers Self-supporting towers Rooftop assemblies

210 210 210 210 211 212 213 214 215 215 218 219 219 220 222 222 222 223 223 223 224 225 226 227 227 228 229 231 233 233 234 234 234 235 237 237 239 240 240 244 244 245 246 247 248 249

Dissimilar metals Safety Aligning antennas on a long distance link Inexpensive signal generator Wi-Spy Antenna alignment procedure Surge and lightning protection Power stabilizers & regulators Troubleshooting Building your team Proper troubleshooting technique Common network problems Locally hosted websites Open proxies Open relay hosts Peer-to-peer networking Programs that install themselves (from the Internet) Windows updates Programs that assume a high bandwidth link Windows traffic on the Internet link Worms and viruses Email forwarding loops Large downloads Sending large files Users sending each other files Economy evaluation of improvised wireless Networking Evaluate the Demand Establish Appropriate Incentives Regulatory Environment for Wireless Analyze the Competition Determine Initial and Recurring Costs and Pricing Case study Cheap Internet in Mali Wireless Mesh Network in India Venezuela: Packet radio Spread spectrum Broadband delivery system Chilesincables.org and wirless networking Action Plan for long range wifi 802.11 Appendix A: Channel Allocations Appendix B: Path Loss Appendix C: Cable Sizes OpenWrt Features Introduction

250 251 251 251 252 254 256 257 258 258 260 261 262 263 263 263 264 265 266 266 267 267 267 268 269 270 270 271 271 271 272 272 276 276 279 280 282 283 286 287 288 289 293 294 295 299

What is OpenWrt Wireless networking What's the max distance between radio cards? What's the difference between wired and wireless networks? Wireless network access modes Security in wireless networks Installing OpenWrt Using OpenWrt OpenWrt configuration Sample network configurations Troubleshooting Resetting to defaults Recovering from bad firmware Experimental OpenWrt Wireless Router The Network Environment Obtaining OpenWrt Firmware Flashing to OpenWrt Configure WAN IP Enable boot_wait Uploading New Firmware The First Boot with OpenWrt Accessing the WRT Configuring the WRT Changing Configuration with nvram Configuring OpenWrt as a Routed Wireless Client Setup LAN Interface Wireless Client Configuration Testing Wireless Connectivity Using wl Re-configure WAN Port Configuring DHCP and DNS on OpenWrt Configuring DNSMasq Scheduling Jobs With cron on OpenWrt Time Synchronization on OpenWrt Modify Init Script OpenVPN Termination on OpenWrt Install & Configure OpenVPN Server Create Routing Script Start OpenVPN Using OpenVPN on OpenWrt BGP Routing on OpenWrt with Quagga Install Components on OpenWrt Debugging Quagga Telnet to BGP Daemon Telnet to Zebra Daemon Wireless antenna:Boost your Wi-Fi by Tin Can Waveguide Antenna

299 300 300 300 301 302 303 309 312 319 324 325 325 326 327 327 327 327 327 328 329 329 330 330 331 332 333 334 334 335 336 336 338 341 342 343 344 345 346 348 350 350 353 353 355 357

Theory behind the Cantenna Cantenna Radius Cantenna Length Range of the Cantenna Cantenna Applications Cantenna construction Instructions for building a cantenna Cantenna as dish feed Horn 2 watt wireless amplifier Deep Dish Cylindrical Parabolic Template Biquad Antenna Construction Helical/helix antenna for 2.4 GHz wavelans and/or WiFi applications Wi-Fi vs WiMAX and BridgeMAXX Wireless network and security recommendations Satellites Balloons IEEE 802.22 Super Wi-Fi Laser Link Distributed Systems Software-defined radio Tactical Common Data Link PirateBox Install PirateBox on a Mobile Phone wifi_tether_v3_1-beta6 for android OpenBTS Some important definitions GSM SIP IMS Air interface USRP Asterisk Starting OpenBTS OpenBTS P2.8 "Opelousas" vs the previous P2.6 "Mamou" Real-Time Asterisk Howto use Git and svn together N200 and N210 Device Notes System diagram Build and Install OpenBTS and the transreciever ARFCN :Absolute radio-frequency channel number Command-line interface listed here Build and Install Smqueue Selecting and Configuring a PBX Build and Install the Subscriber Registry and Sipauthserve

363 363 364 365 366 367 370 376 376 377 378 385 409 414 415 420 422 426 426 426 427 428 431 435 436 437 438 439 439 440 440 440 440 441 444 445 446 448 451 453 451 464 465 471 474 474

Sipauthserve 474 RRLP Server 475 Ways to install GNU Radio 476 Using pre-compiled binaries 476 Installing manually from source 493 Installing on Arch Linux 499 Installing GNU Radio on Debian Linux 501 Fedora installation instructions 502 Mandriva installation 506 OpenSUSE installation 506 Building GNU Radio on Ubuntu Linux 510 Installation on the Play Station 3 516 Using GNU Radio 519 USRP FPGA Firmware 521 GNU Radio on Mac OS X 526 Installing GNU Radio on Mac 540 NetBSD installation guide 552 GNU Radio for Windows users 553 How to use GNU Radio 568 UHD Start 636 UHD - Build Guide 638 USB-based devices:UHD - Transport Application Notes 643 Images installation instructions: UHD - Firmware and FPGA Image Application Notes 647 Application Notes 649 UHD - General Application Notes 649 UHD - Device Identification Notes-Identifying USRPs 653 UHD - USRP1 Application Notes 656 UHD - USRP2 and N Series Application Notes 658 UHD - USRP-B1XX Series Application Notes 665 UHD - USRP-E1XX Series Application Notes 667 UHD - Daughterboard Application Notes 669 RFX Mod 676 UHD - Synchronization Application Notes 677 UHD - Internal GPSDO Application Notes 680 UHD - Calibration Application Notes 682 API Documentation 683 Gnuradio + UHD 685 Asterisk 691 Getting Started With Asterisk 692 Installing Linux for Asterisk 694 Obtaining Asterisk PBX 711 Setting up SIP 721 CentOS 5 and Asterisk 1.4.x installation 741 Asterisk and FreePBX on Ubuntu Server 10.10 744 FreePBX 749 Asterisk installation on Fedora Core 2 final 752

Installing Asterisk Real-Time-way one Asterisk RealTime-way 2 asterisk-addons Asterisk RealTime Sip FreeSWITCH OpenBTS to FreeSWITCH MultiBTS network

757 762 768 775 784 785 793

Preface
The convenience, cost-effectiveness and flexibility of email and instant messaging make them extremely valuable for individuals and organizations with even the most limited access to the Internet but Sometimes access to the Internet is completely restricted, and people or activists are forced to use alternative means to distribute and access uncensored information. In 1989, well before the Internet was widespread, some students from the University of Michigan purchased a fax machine to send daily summaries of international media to universities, government entities, hospitals, and major businesses in China to provide an alternative to the government's reports about the events at Tiananmen Square. In 2011, Organisations that track global internet access detected a collapse in traffic in to and out of Egypt and the shut down involved the withdrawal of more than 3,500 Border Gateway Protocol (BGP) routes by Egyptian ISPs. In the other hand slowing down the internet in some countries around the world make most "circumvention" technologies - the software legerdemain that helps dissidents sneak data along the state-controlled networks - nearly useless. No matter how much circumvention you use, if the government slows the network down to a crawl, you can't upload YouTube videos or Facebook postings. So, many computer experts around the world were looking for a cheap and effective way to stay telecommunications networks. But what is the solution?! The idea is based on improvised wireless network. In last few years, it is said that the U.S funds secret 'internet in a suitcase' for dissidents that was leading a global effort to deploy "shadow" internet and mobile phone systems that dissidents can use to undermine repressive governments that seek to silence them by censoring or shutting down telecommunications networks. The US effort, revealed in dozens of interviews, planning documents and classified diplomatic cables obtained by The New York Times, ranges in scale, cost and sophistication. Some projects involve technology that the United States is developing; others pull together tools that have already been created by hackers in a so-called "liberation technology" movement sweeping the globe. See http://www.ushahidi.com/ The project "shadow" internet has brought together an improbable alliance of diplomats and military engineers, young programmers and dissidents from at least a dozen countries.

The group's suitcase project will rely on a version of "mesh network" technology, which can transform devices such as mobiles or personal computers to create an invisible wireless web without a centralised hub. In other words, a voice, picture or email message could hop directly between the modified wireless devices - each one acting as a mini mobile "tower" and phone - and bypass the official network. Meinrath said that the suitcase would include small wireless antennas, which could increase the area of coverage; a laptop to administer the system; thumb drives and CDs to spread the software to more devices and encrypt the communications; and other components lsuch as ethernet cables. Here is the list of components: 1. Directional sector antenna The base station antenna that gets your cellular network up and running. This looks like the 900MHz airMAX model from Ubiquiti Networks. 2. Cellular WiFi router Picks up the signal and creates a WiFi network. 3. USB flash drives. You dont see it in the picture, but theres a laptop involved with this setup, and flash drives are the best way to swap software when the networks not available. Multiple drives make sharing software easy. Speaking of softwareyoure going to need to to bring some along. Gigaom did a great write up of the essential software stack:

Serval Project Enables communication over regular Android smartphones without the need for internet access. Commotion Software that would turn any mobile device, cell phone or router, into another node in a mesh network. Tor Using multiple encrypted nodes, Tor hides your network activity from prying eyes. OpenBTS Can turn existing GSM phones into VoIP devices when coupled with a Commotion network. OpenGSM Open source magic that allows GSM phones to make calls using cheap base stations over various cellular frequency bands. Users should weight the pros and cons of potentially breaking government airwaves regulations before using OpenGSM.

4. CDs/DVDs Blank or pre-burned, its a good idea to have more than one option for sharing data. 5. PicoStation outdoor wireless access point Extends the mesh and provides access to the network. This particular unit is the Ubiuquiti PicoStation M. Ubiquiti Networks PICO2HP 2.4GHz 802.11bg High Power

6. USRP device: The Universal Software Radio Peripheral: https://www.ettus.com/product http://en.wikipedia.org/wiki/Universal_Software_Radio_Peripheral 7. Cell phone / Smartphone Once your software stack is up and running, these are your means of communication. 8. Outdoor wireless antenna These are the Qbiquiti NanoStation M, a pole mounted antenna that can send 150+ Mbps over 15 km. Want one? Ubiquiti Networks NanoStation M2 2.4GHz 802.11n 22 MIMO The project will also rely on the innovations of independent internet and telecommunications developers. It is it possible for unskilled users to employ existing devices like laptops or smartphones to build a wireless network. One mesh network was created around Jalalabad, Afghanistan, as early as six years ago, using technology developed at the Massachusetts Institute of Technology (MIT). Another popular sharing file technology is Bluetooth that can be improvised to send files from phone to phone within a "trusted network" of citizens Additionally, if your access to the Internet is restricted, consider the possibility of conducting peer-to-peer exchanges through alternative means. IrDA (Infrared) and Bluetooth are available in most modern mobile phones and can be used to transfer data over short distances. Other projects, such as "The Pirate Box", use Wi-Fi and free open source software to create mobile file-sharing devices and well discuss using Pirate Box in details later. In countries with low Internet penetration, such as Cuba, USB flash drives have garnered widespread use by people who want to distribute uncensored information. Other technologies that were used by activists during the 2011 political unrest in Libya and Egypt include fax, speak2tweet (a platform launched by Google and Twitter that enables landline users to tweet via voicemail) and SMS. Not only governments can limit or shutting down the internet, some times the natural disasters like earthquakes, floods and even war will lead to the loss of communications infrastructure. . Thats why many scientists and organisations are working together to develop most effective emergency communication structure. All the projects mentioned here are focused on helping people talk to each other and their communities. Many residents of urban areas receive quality wired Internet services that they take for granted. However, the vast distances that wires must cover to make such services available to all communities prevent Internet service providers from supplying the same services to these rural areas. Difficulties in installing and maintaining long lengths of wire among the sparse populations of rural areas make wired connections unappealing. People living in remote areas may also need

connection to a network through which they can receive important information .Wireless is a potentially great way to reach the internet and connect People who can be tens of miles apart from each other. An alternative to the high prices and inconvenience of extending wires to vastly spaced rural residents is improvised wireless Internet service. In fact, in this book well show you the details of existing projects on unconventional wireless methods of Internet access such as wireless mesh networking based on OpenWrt, DD-WRT, OpenBTS, GNURadio, Olsrd, Wi-Fi, WiMAX, Satellites, Balloons ,802.22, laser link, design of improvised Antenna and so on . Here is the right place, you will learn how the most popular technologies can be used to build an improvised wireless data communication but remember we are not here to debate the legal, moral or ethical issues surrounding them all.

Anna Farahmand May 2012

An Introduction to Radio Physics


Wireless communications make use of electromagnetic waves to send signals across long distances. From a users perspective, wireless connections are not particularly different from any other network connection: your web browser, email, and other applications all work as you would expect. But radio waves have some unexpected properties compared to Ethernet cable. For example, its very easy to see the path that an Ethernet cable takes: locate the plug sticking out of your computer, follow the cable to the other end and youve found it! You can also be confident that running many Ethernet cables alongside each other wont cause problems, since the cables effectively keep their signals contained within the wire itself. But how do you know where the waves emanating from your wireless card are going? What happens when these waves bounce off of objects in the room or other buildings in an outdoor link? How can several wireless cards be used in the same area without interfering with each other? In order to build stable high-speed wireless links, it is important to understand how radio waves behave in the real world.

What is a wave? We are all familiar with vibrations or oscillations in various forms: a pendulum, a tree swaying in the wind, and the string of a guitar - these are all examples of oscillations. What they have in common is that something, some medium or object, is swinging in a periodic manner, with a certain number of cycles per unit of time. This kind of wave is sometimes called a mechanical wave, since it is defined by the motion of an object or its propagating medium. When such oscillations travel (that is, when the swinging does not stay bound to one place) then we speak of waves propagating in space. For example, a singer singing creates periodic oscillations in his or her vocal cords. These oscillations periodically compress and decompress the air, and this periodic change of air pressure then leaves the singers mouth and travels, at the speed of sound. A stone plunging into a lake causes a disturbance, which then travels across the lake as a wave. A wave has a certain speed, frequency, and wavelength. These are connected by a simple relation: Speed = Frequency * Wavelength The wavelength (sometimes referred to as lambda, ) is the distance measured from a point on one wave to the equivalent part of the next, for example from the top of one peak to the next. The frequency is the number of whole waves that pass a fixed point in a period of time. Speed is measured in meters/second, frequency is measured in cycles per second (or Hertz, abbreviated Hz), and wavelength is measured in meters. For example, if a wave on water travels at one meter per second, and it oscillates five times per second, then each wave will be twenty centimeters long: 1 meter/second = 5 cycles/second * W W = 1 / 5 meters W = 0.2 meters = 20 cm

Waves also have a property called amplitude. This is the distance from the center of the wave to the extreme of one of its peaks, and can be thought of as the height of a water wave. The relationship between frequency, wavelength, and amplitude are shown in Figure below Waves in water are easy to visualize. Simply drop a stone into the lake and you can see the waves as they move across the water over time. In the case of electromagnetic waves, the part that might be hardest to understand is: What is it that is oscillating? In order to understand that, you need to understand electromagnetic forces.

Wavelength, amplitude, and frequency. For this wave, the frequency is 2 cycles per second, or 2 Hz.

Electromagnetic forces Electromagnetic forces are the forces between electrical charges and currents. Our most direct access to those is when our hand touches a door handle after walking on synthetic carpet, or brushing up against an electrical fence. A more powerful example of electromagnetic forces is the lightning we see during thunderstorms. The electrical force is the force between electrical charges. The magnetic force is the force between electrical currents. Electrons are particles that carry a negative electrical charge. There are other particles too, but electrons are responsible for most of what we need to know about how radio behaves. Let us look at what is happening in a piece of straight wire, in which we push the electrons from one and to the other and back, periodically. At one moment, the top of the wire is negatively charged - all the negative electrons are gathered there. This creates an electric field from plus to minus along the wire. The next moment, the electrons have all been driven to the other side, and the electric field points the other way. As this happens again and again, the electric field vectors (arrows from plus to minus) are leaving the wire, so to speak, and are radiated out into the space around the wire. What we have just described is known as a dipole (because of the two poles, plus and minus), or more commonly a dipole antenna. This is the simplest form of omnidirectional antenna. The motion of the electric field is commonly referred to as an electromagnetic wave. Let us come back to the relation:

Speed = Frequency * Wavelength In the case of electromagnetic waves, the speed is c, the speed of light. c = 300,000 km/s = 300,000,000 m/s = 3*108 m/s c=f* Electromagnetic waves differ from mechanical waves in that they require no medium in which to propagate. Electromagnetic waves will even propagate through the vacuum of space. Powers of ten In physics, math, and engineering, we often express numbers by powers of ten. We will meet these terms again, e.g. in Giga-Hertz (GHz), Centi-meters (cm), Micro-seconds (s), and so on. Multiples of ten NanoMicroMilliInchKiloMegaGiga10 ^ -9 10 ^ -6 10 ^ -3 10 ^ -2 10 ^ 3 10 ^ 6 10 ^ 9 One billionth Millionth 1/1000 1/100 1000 1 million 1 billion n m c k M G

Knowing the speed of light, we can calculate the wavelength for a given frequency. Let us take the example of the frequency of 802.11b wireless networking, which is f = 2.4 GHz = 2,400,000,000 cycles / second wavelength lambda () = c / f = 3*108 / 2.4*109 = 1.25*10 -1 m = 12.5 cm Frequency and wavelength determine most of an electromagnetic waves behavior, from antennas that we build to objects that are in the way of the networks we intend to run. They are responsible for many of the differences between different standards we might be choosing. Therefore, an understanding of the basic ideas of frequency and wavelength helps a lot in practical wireless work.

Polarization Another important quality of electromagnetic waves is polarization. Polarization describes the direction of the electrical field vector. If you imagine a vertically aligned dipole antenna (the straight piece of wire), electrons only move up and down, not sideways (because there is no room to move) and thus electrical fields only ever point up or down, vertically. The field leaving the wire and traveling as a wave has a strict linear (and in this case, vertical) polarization. If we put the antenna flat on the ground, we would find horizontal linear polarization.

Electric field and complementary magnetic field components of an electromagnetic wave. Polarization describes the orientation of the electric field. Linear polarization is just one special case, and is never quite so perfect: in general, we will always have some component of the field pointing other directions too. The most general case is elliptic polarization, with the extremes of linear (only one direction) and circular polarizations (both directions at equal strength). As one can imagine, polarization becomes important when aligning antennas. If you ignore polarization, you might have very little signal even though you have the strongest antennas. We call this polarization mismatch.

The electromagnetic spectrum Electromagnetic waves span a wide range of frequencies (and, accordingly, wavelengths). This range of frequencies and wavelengths is called the electromagnetic spectrum. The part of the spectrum most familiar to humans is probably light, the visible portion of the electromagnetic spectrum. Light lies roughly between the frequencies of 7.5*1014 Hz and 3.8*1014 Hz, corresponding to wavelengths from circa 400 nm (violet/blue) to 800 nm (red). We are also regularly exposed to other regions of the electromagnetic spectrum, including Alternating Current (AC) or grid electricity at 50/60 Hz, Ultraviolet (on the higher frequencies side of visible light), Infrared (on the lower frequencies side of visible light), X-Rays / Roentgen radiation, and many others. Radio is the term used for the portion of the electromagnetic spectrum in which waves can be generated by applying alternating current to an antenna. This is true for the range from 3 Hz to 300 GHz, but in the more narrow sense of the term, the upper frequency limit would be 1 GHz. When talking about radio, many people think of FM radio, which uses a frequency around 100 MHz. In between radio and infrared we find the region of microwaves - with frequencies from

about 1 GHz to 300 GHz, and wavelengths from 30 cm to 1 mm. The most popular use of microwaves might be the microwave oven, which in fact works in exactly the same region as the wireless standards we are dealing with. These regions lie within the bands that are being kept open for general unlicensed use. This region is called the ISM band, which stands for Industrial, Scientific, and Medical. Most other parts of the electromagnetic spectrum are tightly controlled by licensing legislation, with license values being a huge economic factor. This goes especially for those parts of the spectrum that are suitable for broadcast (TV, radio) as well as voice and data communication. In most countries, the ISM bands have been reserved for unlicensed use.

The electromagnetic spectrum

The frequencies most interesting to us are 2.400 - 2.495 GHz, which is used by the 802.11b and 802.11g radio standards (corresponding to wavelengths of about 12.5 cm). Other commonly available equipment uses the 802.11a standard, which operates at 5.150 - 5.850 GHz (corresponding to wavelengths of about 5 to 6 cm).

Bandwidth A term you will meet often in radio physics is bandwidth. Bandwidth is simply a measure of frequency range. If a range of 2.40 GHz to 2.48 GHz is used by a device, then the bandwidth would be 0.08 GHz (or more commonly stated as 80MHz). It is easy to see that the bandwidth we define here is closely related to the amount of data you can transmit within it - the more room in frequency space, the more data you can fit in at a given moment. The term bandwidth is often used for something we should rather call a data rate, as in my Internet connection has 1 Mbps of bandwidth, meaning it can transmit data at 1 megabit per second.

Frequencies and channels Let us look a bit closer at how the 2.4GHz band is used in 802.11b. The spectrum is divided into evenly sized pieces distributed over the band as individual channels. Note that channels are 22MHz wide, but are only separated by 5MHz. This means that adjacent channels overlap, and can interfere with each other. This is represented visually in Figure below.

Channels and center frequencies for 802.11b. Note that channels 1, 6, and 11 do not overlap.

Behavior of radio waves There are a few simple rules of thumb that can prove extremely useful when making first plans for a wireless network: The longer the wavelength, the further it goes The longer the wavelength, the better it travels through and around things The shorter the wavelength, the more data it can transport All of these rules, simplified as they may be, are rather easy to understand by example.

Longer waves travel further Assuming equal power levels, waves with longer wavelengths tend to travel further than waves with shorter wavelengths. This effect is often seen in FM radio, when comparing the range of an FM transmitter at 88MHz to the range at 108MHz. Lower frequency transmitters tend to reach much greater distances than high frequency transmitters at the same power.

Longer waves pass around obstacles A wave on water which is 5 meters long will not be stopped by a 5 mm piece of wood sticking out of the water. If instead the piece of wood were 50 meters big (e.g. a ship), it would be well in the way of the wave. The distance a wave can travel depends on the relationship between the wavelength of the wave and the size of obstacles in its path of propagation. It is harder to visualize waves moving through solid objects, but this is the case with electromagnetic waves. Longer wavelength (and therefore lower frequency) waves tend to penetrate objects better than shorter wavelength (and therefore higher frequency) waves. For example, FM radio (88- 108MHz) can travel through buildings and other obstacles easily, while

shorter waves (such as GSM phones operating at 900MHz or 1800MHz) have a harder time penetrating buildings. This effect is partly due to the difference in power levels used for FM radio and GSM, but is also partly due to the shorter wavelength of GSM signals.

Shorter waves can carry more data The faster the wave swings or beats, the more information it can carry - every beat or cycle could for example be used to transport a digital bit, a '0' or a '1', a 'yes' or a 'no'. There is another principle that can be applied to all kinds of waves, and which is extremely useful for understanding radio wave propagation. This principle is known as the Huygens Principle, named after Christiaan Huygens, Dutch mathematician, physicist and astronomer 1629 - 1695. Imagine you are taking a little stick and dipping it vertically into a still lake's surface, causing the water to swing and dance. Waves will leave the center of the stick - the place where you dip in in circles. Now, wherever water particles are swinging and dancing, they will cause their eighbor particles to do the same: from every point of disturbance, a new circular wave will start. This is, in simple form, the Huygens principle. In the words of wikipedia.org: The Huygens' principle is a method of analysis applied to problems of wave propagation in the far field limit. It recognizes that each point of an advancing wave front is in fact the center of a fresh disturbance and the source of a new train of waves; and that the advancing wave as a whole may be regarded as the sum of all the secondary waves arising from points in the medium already traversed. This view of wave propagation helps better understand a variety of wave phenomena, such as diffraction. This principle holds true for radio waves as well as waves on water, for sound as well as light only for light the wavelength is far too short for human beings to actually see the effects directly. This principle will help us to understand diffraction as well as Fresnel zones, the need for line of sight as well as the fact that sometimes we seem to be able to go around corners, with no line of sight. Let us now look into what happens to electromagnetic waves as they travel.

Absorption When electromagnetic waves go through 'something' (some material), they generally get weakened or dampened. How much they lose in power will depend on their frequency and of course the material. Clear window glass is obviously transparent for light, while the glass used in sunglasses filter out quite a share of the light intensity and also the ultraviolet radiation. Often, an absorption coefficient is used to describe a materials impact on Radiation. For microwaves, the two main absorbent materials are:

Metal. Electrons can move freely in metals, and are readily able to swing and thus absorb the energy of a passing wave. Water. Microwaves cause water molecules to jostle around, thus taking away some of the waves energy. For the purpose of practical wireless networking, we may well consider metal and water perfect absorbers: we will not be able to go through them (al-though thin layers of water will let some power pass). They are to microwave what a brick wall is to light. When talking about water, we have to remember that it comes in different forms: rain, fog and mist, low clouds and so forth all will be in the way of radio links. They have a strong influence, and in many circumstances a change in weather can bring a radio link down. There are other materials that have a more complex effect on radio absorption. For trees and wood, the amount of absorption depends on how much water they contain. Old dead dry wood is more or less transparent, wet fresh wood will absorb a lot. Note: A commonly held myth is that water resonates at 2.4 GHz, which is why that frequency is used in microwave ovens. Actually, water doesnt appear to have any particular resonant frequency. Water spins and jostles around near radio, and will heat when in the presence of high power radio waves at just about any frequency. 2.4 GHz is an unlicensed ISM frequency, and so was a good political choice for use in microwave ovens. Plastics and similar materials generally do not absorb a lot of radio energy but this varies depending on the frequency and type of material. Before you build a component from plastic (e.g. weather protection for a radio device and its antennas), it is always a good idea to measure and verify that the material does not absorb radio energy around 2.4GHz. One simple method of measuring the absorption of plastic at 2.4GHz is to put a sample in a microwave oven for a couple of minutes. If the plastic heats up, then it absorbs radio energy and should not be used for weatherproofing. Lastly, let us talk about ourselves: humans (as well as other animals) are largely made out of water. As far as radio networking is concerned, we may well be described as big bags of water, with the same strong absorption. Orienting an office access point in such a way that its signal must pass through many people is a key mistake when building office networks. The same goes for hotspots, cafe installations, libraries, and outdoor installations.

Reflection Just like visible light, radio waves are reflected when they come in contact with materials that are suited for that: for radio waves, the main sources of reflection are metal and water surfaces. The rules for reflection are quite simple: the angle at which a wave hits a surface is the same angle at which it gets deflected. Note that in the eyes of a radio wave, a dense grid of bars acts just the same as a solid surface, as long as the distance between bars is small compared to the wavelength. At 2.4GHz, a one cm metal grid will act much the same as a metal plate.

Although the rules of reflection are quite simple, things can become very complicated when you imagine an office interior with many small metal objects of various complicated shapes. The same goes for urban situations: Look around you in city environment and try to spot all of the metal objects. This explains why multipath effects (i.e. signal reaching their target along different paths, and therefore at different times) play such an important role in wireless networking. Water surfaces, with waves and ripples changing all the time, effectively make for a very complicated reflection object which is more or less impossible to calculate and predict precisely.

Reflection of radio waves. The angle of incidence is always equal to the angle of reflection. A parabolic uses this effect to concentrate radio waves spread out over its surface in a common direction. We should also add that polarization has an impact: waves of different polarization in general will be reflected differently. We use reflection to our advantage in antenna building: e.g. we put huge parabolas behind our radio transmitter/receiver to collect and bundle the radio signal into a fine point.

Diffraction Diffraction is the apparent bending of waves when hitting an object. It is the effect of waves going around corners. Imagine a wave on water traveling in a straight wave front, just like a wave that we see rolling onto an ocean beach. Now we put a solid barrier, say a wooden solid fence, in its way to block it. We cut a narrow slit opening into that wall, like a small door. From this opening, a circular wave will start, and it will of course reach points that are not in a direct line behind this opening, but also on either side of it. If you look at this wavefront - and it might

just as well be an electromagnetic wave - as a beam (a straight line), it would be hard to explain how it can reach points that should be hidden by a barrier. When modeled as a wavefront, the phenomenon makes sense.

Diffraction through a narrow slit The Huygens Principle provides one model for understanding this behavior. Imagine that at any given instant, every point on a wavefront can be considered the starting point for a spherical wavelet. This idea was later extended by Fresnel, and whether it adequately describes the phenomenon is still a matter of debate. But for our purposes, the Huygens model describes the effect quite well.

The Huygens Principle

Through means of the effect of diffraction, waves will bend around corners or through an opening in a barrier. The wavelengths of visible light are far too small for humans to observe this effect directly. Microwaves, with a wavelength of several centimeters, will show the effects of diffraction when waves hit walls, mountain peaks, and other obstacles. It seems as if the obstruction causes the wave to change its direction and go around corners.

Diffraction over a mountain top. Note that diffraction comes at the cost of power: the energy of the diffracted wave is significantly less than that of the wavefront that caused it. But in some very specific applications, you can take advantage of the diffraction effect to circumvent obstacles.

Interference When working with waves, one plus one does not necessarily equal two. It can also result in zero.

Constructive and destructive interference

This is easy to understand when you draw two sine waves and add up the amplitudes. When peak hits peak, you will have maximum results (1 + 1 = 2). This is called constructive interference. When peak hits valley, you will have complete annihilation ((1 + (-)1 = 0) - destructive interference. You can actually try this with waves on water and two little sticks to create circular waves - you will see that where two waves cross, there will be areas of higher wave peaks and others that remain almost flat and calm. In order for whole trains of waves to add up or cancel each other out perfectly, they would have to have the exact same wavelength and a fixed phase relation, this means fixed positions from the peaks of the one wave to the others. In wireless technology, the word Interference is typically used in a wider sense, for disturbance through other RF sources, e.g. neighboring channels. So, when wireless networkers talk about interference they typically talk about all kinds of disturbance by other networks, and other sources of microwave. Interference is one of the main sources of difficulty in building wireless links, especially in urban environments or closed spaces (such as a conference space) where many networks may compete for use of the spectrum. Whenever waves of equal amplitude and opposite phase cross paths, the wave is annihilated and no signal can be received. The much more common case is that waves will combine to form a completely garbled waveform that cannot be effectively used for communication. The modulation techniques and use of multiple channels help to deal with the problem of interference,but does not completely eliminate it.

Line of sight The term line of sight, often abbreviated as LOS, is quite easy to understand when talking about visible light: if we can see a point B from point A where we are, we have line of sight. Simply draw a line from A to B, and if nothing is in the way, we have line of sight. Things get a bit more complicated when we are dealing with microwaves. Remember that most propagation characteristics of electromagnetic waves scale with their wavelength. This is also the case for the widening of waves as they travel. Light has a wavelength of about 0.5 micrometers, microwaves as used in wireless networking have a wavelength of a few centimeters. Consequently, their beams are a lot wider - they need more space, so to speak. Note that visible light beams widen just the same, and if you let them travel long enough, you can see the results despite of their short wavelength. When pointing a well focussed laser at the moon, its beam will widen to well over 100 meters in radius by the time it reaches the surface. You can see this effect for yourself using an inexpensive laser pointer and a pair of binoculars on a clear night. Rather than pointing at the moon, point at a distant mountain or unoccupied structure (such as a water tower). The radius of your beam will increase as the distance increases.The line of sight that we need in order to have an optimal wireless connection from A to B is more than just a thin line - its shape is more like that of a cigar,an ellipse. Its width can be described by the concept of Fresnel zones.

Understanding the Fresnel zone The exact theory of Fresnel (pronounced Fray-nell) zones is quite complicated. However, the concept is quite easy to understand: we know from the Huygens principle that at each point of a wavefront new circular waves start, We know that microwave beams widen as they leave the antenna. We know that waves of one frequency can interfere with each other. Fresnel zone theory simply looks at a line from A to B, and then at the space around that line that contributes to what is arriving at point B. Some waves travel directly from A to B, while others travel on paths off axis. Consequently, their path is longer, introducing a phase shift between the direct and indirect beam. Whenever the phase shift is one full wavelength, you get constructive interference: the signals add up optimally. Taking this approach and calculating accordingly, you find there are ring zones around the direct line A to B which contribute to the signal arriving at point B.

The Fresnel zone is partially blocked on this link, although the visual line of sight appears clear Note that there are many possible Fresnel zones, but we are chiefly concerned with zone 1. If this area were partially blocked by an obstruction, e.g. a tree or a building, the signal arriving at the far end would be diminished. When building wireless links, we therefore need to be sure that these zones be kept free of obstructions. Of course, nothing is ever perfect, so usually in wireless networking we check that about 60 percent of the radius of the first Fresnel zone should be kept free. Here is one formula for calculating the first Fresnel zone: r = 17.31 * sqrt((d1*d2)/(f*d)) ...where r is the radius of the zone in meters, d1 and d2 are distances from the obstacle to the link end points in meters, d is the total link distance in meters, and f is the frequency in MHz. Note that this gives you the radius of the zone, not the height above ground. To calculate the height above ground, you need to subtract the result from a line drawn directly between the tops of the two towers. For example, lets calculate the size of the first Fresnel zone in the middle of a 2km link, transmitting at 2.437GHz (802.11b channel 6): r = 17.31 sqrt((1000 * 1000) / (2437 * 2000)) r = 17.31 sqrt(1000000 / 4874000) r = 7.84 meters

Assuming both of our towers were ten meters tall, the first Fresnel zone would pass just 2.16 meters above ground level in the middle of the link. But how tall could a structure at that point be to clear 60% of the first zone? r = 0.6 * 17.31 sqrt((1000 * 1000) / (2437 * 2000)) r = 0.6 * 17.31 sqrt(600000 / 4874000) r = 4.70 meters Subtracting the result from 10 meters, we can see that a structure 5.3 meters tall at the center of the link would block up to 40% of the first Fresnel zone. This is normally acceptable, but to improve the situation we would need to position our antennas higher up, or change the direction of the link to avoid the obstacle.

Power Any electromagnetic wave carries energy - we can feel that when we enjoy (or suffer from) the warmth of the sun. The amount of energy received in a certain amount of time is called power. The power P is of key importance for making wireless links work: you need a certain minimum power in order for a receiver to make sense of the signal. We will come back to details of transmission power, losses, gains and radio sensitivity later. Here we will briefly discuss how the power P is defined and measured. The electric field is measured in V/m (potential difference per meter), the power contained within it is proportional to the square of the electric field P ~ E2 Practically, we measure the power by means of some form of receiver, e.g. an antenna and a voltmeter, power meter, oscilloscope, or even a radio card and laptop. Looking at the signals power directly means looking at the square of the signal in Volts.

Calculating with dB By far the most important technique when calculating power is calculating with decibels (dB). There is no new physics hidden in this - it is just a convenient method which makes calculations a lot simpler. The decibel is a dimensionless unit2, that is, it defines a relationship between two measurements of power. It is defined by: dB = 10 * Log (P1 / P0) Where P1 and P0 can be whatever two values you want to compare. Typically, in our case, this will be some amount of power. Why are decibels so handy to use? Many phenomena in nature happen to behave in a way we call exponential. For example, the human ear senses a sound to be twice as loud as another one if it has ten times the physical signal. Another example, quite close to our field of interest, is absorption. Suppose a wall is in the path of our wireless link, and each meter of wall takes away half of the available signal. The result would be:

0 meters = 1 (full signal) 1 meter = 1/2 2 meters = 1/4 3 meters = 1/8 4 meters = 1/16 n meters = 1/2n = 2 -n This is exponential behavior. But once we have used the trick of applying the logarithm (log), things become a lot easier: instead of taking a value to the n-th power, we just multiply by n. Instead of multiplying values, we just add. Here are some commonly used values that are important to remember: +3 dB = double power -3 dB = half the power +10 dB = order of magnitude (10 times power) -10 dB = one tenth power Note: Another example of a dimensionless unit is the percent (%) which can also be used in all kinds of quantities or numbers. While measurements like feet and grams are fixed, dimensionless units represent a relationship. In addition to dimensionless dB, there are a number of relative definitions that are based on a certain base value P0. The most relevant ones for us are: dBm relative to P0 = 1 mW dBi relative to an ideal isotropic antenna An isotropic antenna is a hypothetical antenna that evenly distributes power in all directions. It is approximated by a dipole, but a perfect isotropic antenna cannot be built in reality. The isotropic model is useful for describing the relative power gain of a real world antenna. Another common (although less convenient) convention for expressing power is in milliwatts. Here are equivalent power levels expressed in milliwatts and dBm: 1 mW = 0 dBm 2 mW = 3 dBm 100 mW = 20 dBm 1 W = 30 dBm Most people find it difficult to understand phenomenon that they cant even see with their own eyes. By now you should understand that radio waves dont travel in a straight, predictable path. To make reliable communication networks, you will need to be able to calculate how much power is needed to cross a given distance, and predict how the waves will travel along the way.

Network Design
Before purchasing equipment or deciding on a hardware platform, you should have a clear idea of the nature of your communications problem. You need to connect computer networks together in order to share resources and ultimately reach the larger global Internet. The network design you choose to implement should fit the communications problem you are trying to solve. Do you need to connect a remote site to an Internet connection in the center of your campus? Will your network likely grow to include several remote sites? Will most of your network components be installed in fixed locations, or will your network expand to include hundreds of roaming laptops and other devices? In this chapter, we will begin with a review of the networking concepts that define TCP/IP, the primary family of networking protocols currently used on the Internet. We will then see examples of how other people have built wireless networks to solve their communication problems, including diagrams of the essential network structure. Finally, we will present several common methods for getting your information to flow efficiently through your network and on to the rest of the world.

Networking 101 TCP/IP refers to the suite of protocols that allow conversations to happen on the global Internet. By understanding TCP/IP, you can build networks that will scale to virtually any size, and will ultimately become part of the global Internet. If you are already familiar with the essentials of TCP/IP networking (including addressing, routing, switches, firewalls, and routers),you can skip the chapter. Here we will now review the basics of Internet networking.

Introduction Venice, Italy is a fantastic city to get lost in. The roads are mere foot paths that cross water in hundreds of places, and never go in a simple straight line. Postal carriers in Venice are some of the most highly trained in the world, specializing in delivery to only one or two of the six sestieri (districts) of Venice. This is necessary due to the intricate layout of that ancient city. Many people find that knowing the location of the water and the sun is far more useful than trying to find a street name on a map.

Another kind of network mask.

Imagine a tourist who happens to find papier-mch mask as a souvenir, and wants to have it shipped from the studio in S. Polo, Venezia to an office in Seattle, USA. This may sound like an ordinary (or even trivial) task, but let's look at what actually happens. The artist first packs the mask into a shipping box and addresses it to the office in Seattle, USA. They then hand this off to a postal employee, who attaches some official forms and sends it to a central package processing hub for international destinations. After several days, the package clears Italian customs and finds its way onto a transatlantic flight, arriving at a central import processing location in the U.S. Once it clears through U.S. customs, the package is sent to the regional distribution point for the northwest U.S., then on to the Seattle postal processing center. The package eventually makes its way onto a delivery van which has a route that brings it to the proper address, on the proper street, in the proper neighborhood. A clerk at the office accepts the package and puts it in the proper incoming mail box. Once it arrives, the package is retrieved and the mask itself is finally received. The clerk at the office in Seattle neither knows nor cares about how to get to the sestiere of S. Polo, Venezia. His job is simply to accept packages as they arrive, and deliver them to the proper person. Similarly, the postal carrier in Venice has no need to worry about how to get to the correct neighborhood in Seattle. His job is to pick up packages from his local neighborhood and forward them to the next closest hub in the delivery chain.

Internet networking. Packets are forwarded between routers until they reach their ultimate destination. This is very similar to how Internet routing works. A message is split up into many individual packets, and are labeled with their source and destination. The computer then sends these packets to a router, which decides where to send them next. The router needs only to keep track of a handful of routes (for example, how to get to the local network, the best route to a few other local networks, and one route to a gateway to the rest of the Internet). This list of possible routes is called the routing table. As packets arrive at the router, the destination address is examined and compared against its internal routing table. If the router has no explicit route to the destination in question, it sends the packet to the closest match it can find, which is often its own Internet gateway (via the default route). And the next router does the same, and so forth, until the packet eventually arrives at its destination. Packages can only make their way through the

international postal system because we have established a standardized addressing scheme for packages. For example, the destination address must be written legibly on the front of the package, and include all critical information (such as the recipient's name, street address, city, country, and postal code). Without this information, packages are either returned to the sender or are lost in the system. Packets can only flow through the global Internet because we have agreed on a common addressing scheme and protocol for forwarding packets. These standard communication protocols make it possible to exchange information on a global scale.

Cooperative communications Communication is only possible when the participants speak a common language. But once the communication becomes more complex than a simple conversation between two people, protocol becomes just as important as language. All of the people in an auditorium may speak English, but without a set of rules in place to establish who has the right to use the microphone, the communication of an individuals ideas to the entire room is nearly impossible. Now imagine an auditorium as big as the world, full of all of the computers that exist. Without a common set of communication protocols to regulate when and how each computer can speak, the Internet would be a chaotic mess where every machine tries to speak at once. People have developed a number of communications frameworks to address this problem. The most well-known of these is the OSI model.

The OSI model The international standard for Open Systems Interconnection (OSI) is defined by the document ISO/IEC 7498-1, as outlined by the International Standards Organization and the International Electrotechnical Commission. The full standard is available as publication "ISO/IEC 74981:1994," available from http://standards.iso.org/ittf/PubliclyAvailableStandards/. The OSI model divides network traffic into a number of layers. Each layer is independent of the layers around it, and each builds on the services provided by the layer below while providing new services to the layer above. The abstraction between layers makes it easy to design elaborate and highly reliable protocol stacks, such as the ubiquitous TCP/IP stack. A protocol stack is an actual implementation of a layered communications framework. The OSI model doesn't define the protocols to be used in a particular network, but simply delegates each communications "job" to a single layer within a welldefined hierarchy. While the ISO/IEC 7498-1 specification details how layers should interact with each other, it leaves the actual implementation details up to the manufacturer. Each layer can be implemented in hardware (more common for lower layers) or software. As long as the interface between layers adheres to the standard, implementers are free to use whatever means are available to build their protocol stack. This means that any given layer from manufacturer A can operate with the same layer from manufacturer B (assuming the relevant specifications are implemented and interpreted correctly). Here is a brief outline of the seven-layer OSI networking model:

Layer 7

Name Applicatio n Presentati on Session Transport

6 5 4

Network

Data Link

Physical

Description The Application Layer is the layer that most network users are exposed to, and is the level at which human communication happens. HTTP, FTP, and SMTP are all application layer protocols. The human sits above this layer, interacting with the application. The Presentation Layer deals with data representation, before it reaches the application. This would include MIME encoding, data compression, formatting checks, byte ordering, etc. The Session Layer manages the logical communications session between applications. NetBIOS and RPC are two examples of a layer five protocol. The Transport Layer provides a method of reaching a particular service on a given network node. Examples of protocols that operate at this layer are TCP and UDP. Some protocols at the transport layer (such as TCP) ensure that all of the data has arrived at the destination, and is reassembled and delivered to the next layer in the proper order. UDP is a "connectionless" protocol commonly used for video and audio streaming. IP (the Internet Protocol) is the most common Network Layer protocol. This is the layer where routing occurs. Packets can leave the link local network and be retransmitted on other networks. Routers perform this function on a network by having at least two network interfaces, one on each of the networks to be interconnected. Nodes on the Internet are reached by their globally unique IP address. Another critical Network Layer protocol is ICMP, which is a special protocol which provides various management messages needed for correct operation of IP. This layer is also sometimes referred to as the Internet Layer. Whenever two or more nodes share the same physical medium (for example, several computers plugged into a hub, or a room full of wireless devices all using the same radio channel) they use the Data Link Layer to communicate. Common examples of data link protocols are Ethernet, Token Ring, ATM, and the wireless networking protocols (802.11a/b/g). Communication on this layer is said to be link-local, since all nodes connected at this layer communicate with each other directly. This layer is sometimes known as the Media Access Control (MAC) layer. On networks modeled after Ethernet, nodes are referred to by their MAC address. This is a unique 48 bit number assigned to every networking device when it is manufactured. The Physical Layer is the lowest layer in the OSI model, and refers to the actual physical medium over which communications take place. This can be a copper CAT5 cable, a fiber optic bundle, radio waves, or just about any other medium capable of transmitting signals. Cut wires, broken fiber, and RF interference are all physical layer problems.

The layers in this model are numbered one through seven, with seven at the top. This is meant to reinforce the idea that each layer builds upon, and depends upon, the layers below. Imagine the OSI model as a building, with the foundation at layer one, the next layers as successive floors, and the roof at layer seven. If you remove any single layer, the building will not stand. Similarly, if the fourth floor is on fire, then nobody can pass through it in either direction. The first three layers (Physical, Data Link, and Network) all happen "on the network." That is, activity at these layers is determined by the configuration of cables, switches, routers, and similar devices. A network switch can only distribute packets by using MAC addresses, so it need only implement layers one and two. A simple router can route packets using only their IP addresses, so it need implement only layers one through three. A web server or a laptop computer runs applications, so it must implement all seven layers. Some advanced routers may implement layer four and above, to allow them to make decisions based on the higher-level information content in a packet, such as the name of a website, or the attachments of an email. The OSI model is internationally recognized, and is widely regarded as the complete and definitive network model. It provides a framework for manufacturers and network protocol implementers that can be used to build networking devices that interoperate in just about any part of the world. From the perspective of a network engineer or troubleshooter, the OSI model can seem needlessly complex. In particular, people who build and troubleshoot TCP/IP networks rarely need to deal with problems at the Session or Presentation layers. For the majority of Internet network implementations, the OSI model can be simplified into a smaller collection of five layers.

The TCP/IP model Unlike the OSI model, the TCP/IP model is not an international standard and its definitions vary. Nevertheless, it is often used as a pragmatic model for understanding and troubleshooting Internet networks. The vast majority of the Internet uses TCP/IP, and so we can make some assumptions about networks that make them easier to understand. The TCP/IP model of networking describes the following five layers: Layer Name 5 Application 4 Transport 3 Internet 2 Data Link 1 Physical In terms of the OSI model, layers five through seven are rolled into the topmost layer (the Application layer). The first four layers in both models are identical. Many network engineers think of everything above layer four as "just data" that varies from application to application. Since the first three layers are interoperable between virtually all manufacturers' equipment, and layer four works between all hosts using TCP/IP, and everything above layer four tends to apply to specific applications, this simplified model works well when building and troubleshooting

TCP/IP networks. We will use the TCP/IP model when discussing networks here. The TCP/IP model can be compared to a person delivering a letter to a downtown office building. The person first needs to interact with the road itself (the Physical layer), pay attention to other traffic on the road (the Data Link layer), turn at the proper place to connect to other roads and arrive at the correct address (the Internet layer), go to the proper floor and room number (the Transport layer), and finally give it to a receptionist who can take the letter from there (the Application layer). Once they have delivered the message to the receptionist, the delivery person is free to go on their way. The five layers can be easily remembered by using the mnemonic Please Dont Look in the Attic, which of course stands for Physical / Data Link / Internet / Transport / Application.

The Internet protocols TCP/IP is the protocol stack most commonly used on the global Internet. The acronym stands for Transmission Control Protocol (TCP) and Internet Protocol (IP), but actually refers to a whole family of related communications protocols. TCP/IP is also called the Internet protocol suite, and it operates at layers three and four of the TCP/IP model. In this discussion, we will focus on version four of the IP protocol (IPv4) as this is now the most widely deployed protocol on the Internet.

IP Addressing In an IPv4 network, the address is a 32-bit number, normally written as four 8-bit numbers expressed in decimal form and separated by periods. Examples of IP addresses are 10.0.17.1, 192.168.1.1, or 172.16.5.23. If you enumerated every possible IP address, they would range from 0.0.0.0 to 255.255.255.255. This yields a total of more than four billion possible IP addresses (255 x 255 x 255 x 255 = 4,228,250,625); although many of these are reserved for special purposes and should not be assigned to hosts. Each of the usable IP addresses is a unique identifier that distinguishes one network node from another. Interconnected networks must agree on an IP addressing plan. IP addresses must be unique and generally cannot be used in different places on the Internet at the same time; otherwise, routers would not know how best to route packets to them. IP addresses are allocated by a central numbering authority that provides a consistent and coherent numbering method. This ensures that duplicate addresses are not used by different networks. The authority assigns large blocks of consecutive addresses to smaller authorities, who in turn assign smaller consecutive blocks within these ranges to other authorities, or to their customers. These groups of addresses are called sub-networks, or subnets for short. Large subnets can be further subdivided into smaller subnets. A group of related addresses is referred to as an address space.

Without unique IP addresses, unambiguous global routing is impossible. If the PC requests a web page from 10.1.1.2, which server will it reach?

Subnets By applying a subnet mask (also called a network mask, or simply netmask) to an IP address, you can logically define both a host and the network to which it belongs. Traditionally, subnet masks are expressed using dotted decimal form, much like an IP address. For example, 255.255.255.0 is one common net-mask. You will find this notation used when configuring network interfaces, creating routes, etc. However, subnet masks are more succinctly expressed using CIDR notation, which simply enumerates the number of bits in the mask after a forward slash (/). Thus, 255.255.255.0 can be simplified as /24. CIDR is short for Classless InterDomain Routing, and is defined in RFC1518. A subnet mask determines the size of a given network. Using a /24 netmask, 8 bits are reserved for hosts (32 bits total - 24 bits of netmask = 8 bits for hosts). This yields up to 256 possible host addresses (28 = 256). By convention, the first value is taken as the network address (.0 or 00000000), and the last value is taken as the broadcast address (.255 or 11111111). This leaves 254 addresses available for hosts on this network. Subnet masks work by applying AND logic to the 32 bit IP number. In binary notation, the "1" bits in the mask indicate the network address portion, and "0" bits indicate the host address portion. A logical AND is performed by comparing two bits. The result is "1" if both of the bits being compared are also "1". Otherwise the result is "0". Here are all of the possible outcomes of a binary AND comparison between two bits. Note: RFC is short for Request For Comments. RFCs are a numbered series of documents published by the Internet Society that document ideas and concepts related to Internet technologies.Not all RFCs are actual standards. RFCs can be viewed online at http://rfc.net/

Bit 1 Bit 2 Result 0 0 0 0 1 0 1 0 0 1 1 1 To understand how a netmask is applied to an IP address, first convert everything to binary. The netmask 255.255.255.0 in binary contains twenty-four "1" bits: 255 255 255 0 11111111.11111111.11111111.00000000 When this netmask is combined with the IP address 10.10.10.10, we can apply a logical AND to each of the bits to determine the network address. 10.10.10.10:00001010.00001010.00001010.00001010 255.255.255.0:11111111.11111111.11111111.00000000 ----------------------------------10.10.10.0:00001010.00001010.00001010.00000000 This results in the network 10.10.10.0/24. This network consists of the hosts 10.10.10.1 through 10.10.10.254, with 10.10.10.0 as the network address and 10.10.10.255 as the broadcast address. Subnet masks are not limited to entire octets. One can also specify subnet masks like 255.254.0.0 (or /15 CIDR). This is a large block, containing 131,072 addresses, from 10.0.0.0 to 10.1.255.255. It could be further subdivided, for example into 512 subnets of 256 addresses each. The first one would be 10.0.0.0-10.0.0.255, then 10.0.1.0-10.0.1.255, and so on up to 10.1.255.010.1.255.255. Alternatively, it could be subdivided into 2 blocks of 65,536 addresses, or 8192 blocks of 16 addresses, or in many other ways. It could even be subdivided into a mixture of different block sizes, as long as none of them overlap, and each is a valid subnet whose size is a power of two. While many netmasks are possible, common netmasks include: Decimal # of Hosts CIDR /30 255.255.255.252 4 /29 255.255.255.248 8 /28 255.255.255.240 16 /27 255.255.255.224 32 /26 255.255.255.192 64 /25 255.255.255.128 128 /24 255.255.255.0 256 /16 255.255.0.0 65 536 /8 255.0.0.0 16 777 216

With each reduction in the CIDR value the IP space is doubled. Remember that two IP addresses within each network are always reserved for the network and broadcast addresses. There are three common netmasks that have special names. A /8 network (with a netmask of 255.0.0.0) defines a Class A network. A /16 (255.255.0.0) is a Class B, and a /24 (255.255.255.0) is called a Class C. These names were around long before CIDR notation, but are still often used for historical reasons.

Global IP Addresses Have you ever wondered who controls the allocation of IP space? Globally routable IP addresses are assigned and distributed by Regional Internet Registrars (RIRs) to ISPs. The ISP then allocates smaller IP blocks to their clients as required. Virtually all Internet users obtain their IP addresses from an ISP. The 4 billion available IP addresses are administered by the Internet Assigned Numbers Authority (IANA, http://www.iana.org). IANA has divided this space into large subnets, usually /8 subnets with 16 million addresses each. These subnets are delegated to one of the five regional Internet registries (RIRs), which are given authority over large geographic areas.

Authority for Internet IP address assignments is delegated to the five Regional Internet Registrars. The five RIRs are: African Network Information Centre (AfriNIC, http://www.afrinic.net ) Asia Pacific Network Information Centre (APNIC, http://www.apnic.net /) American Registry for Internet Numbers (ARIN, http://www.arin.net ) Regional Latin-American and Caribbean IP Address Registry (LACNIC http://www.lacnic.net ) Rseaux IP Europens (RIPE NCC, http://www.ripe.net ) Your ISP will assign globally routable IP address space to you from the poolallocated to it by your RIR. The registry system assures that IP addresses are not reused in any part of the network anywhere in the world. Once

IP address assignments have been agreed upon, it is possible to pass packets between networks and participate in the global Internet. The process of moving packets between networks is called routing.

Static IP Addresses A static IP address is an address assignment that never changes. Static IP addresses are important because servers using these addresses may have DNS mappings pointed towards them, and typically serve information to other machines (such as email services, web servers, etc.). Blocks of static IP addresses may be assigned by your ISP, either by request or automatically depending on your means of connection to the Internet.

Dynamic IP Addresses Dynamic IP addresses are assigned by an ISP for non-permanent nodes connecting to the Internet, such as a home computer which is on a dial-up connection. Dynamic IP addresses can be assigned automatically using the Dynamic Host Configuration Protocol (DHCP), or the Point-to-Point Protocol (PPP), depending on the type of Internet connection. A node using DHCP first requests an IP address assignment from the network, and automatically configures its network interface. IP addresses can be assigned randomly from a pool by your ISP, or might be assigned according to a policy. IP addresses assigned by DHCP are valid for a specified time (called the lease time). The node must renew the DHCP lease before the lease time expires. Upon renewal, the node may receive the same IP address or a different one from the pool of available addresses. Dynamic addresses are popular with Internet service providers, because it enables them to use fewer IP addresses than their total number of customers. They only need an address for each customer who is active at any one time. Globally routable IP addresses cost money, and some authorities that specialize in the assignment of addresses (such as RIPE, the European RIR) are very strict on IP address usage for ISP's. Assigning addresses dynamically allows ISPs to save money, and they will often charge extra to provide a static IP address to their customers.

Private IP addresses Most private networks do not require the allocation of globally routable, public IP addresses for every computer in the organization. In particular, computers which are not public servers do not need to be addressable from the public Internet. Organizations typically use IP addresses from

the private address space for machines on the internal network. There are currently three blocks of private address space reserved by IANA: 10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16. These are defined in RFC1918. These addresses are not intended to be routed on the Internet, and are typically unique only within an organization or group of organizations which choose to follow the same numbering scheme.

RFC1918 private addresses may be used within an organization, and are not routed on the global Internet. If you ever intend to link together private networks that use RFC1918 address space, be sure to use unique addresses throughout all of the networks. For example, you might break the 10.0.0.0/8 address space into multiple Class B networks (10.1.0.0/16, 10.2.0.0/16, etc.). One block could be assigned to each network according to its physical location (the campus main branch, field office one, field office two, dormitories, and so forth). The network administrators at each location can then break the network down further into multiple Class C networks (10.1.1.0/24, 10.1.2.0/24, etc.) or into blocks of any other logical size. In the future, should the networks ever be linked (either by a physical connection, wireless link, or VPN), then all of the machines will be reachable from any point in the network without having to renumber network devices. Some Internet providers may allocate private addresses like these instead of public addresses to their customers, although this has serious disadvantages. Since these addresses cannot be routed over the Internet, computers which use them are not really "part" of the Internet, and are not directly reachable from it. In order to allow them to communicate with the Internet, their private addresses must be translated to public addresses. This translation process is known as Network Address Translation (NAT), and is normally performed at the gateway between the private network and the Internet. We will look at NAT in more detail later.

Routing Imagine a network with three hosts: A, B, and C. They use the corresponding IP addresses 192.168.1.1, 192.168.1.2 and 192.168.1.3. These hosts are part of a /24 network (their network mask is 55.255.255.0). For two hosts to communicate on a local network, they must determine each others' MAC addresses. It is possible to manually configure each host with a mapping table

from IP address to MAC address, but normally the Address Resolution Protocol (ARP) is used to determine this automatically.

Computer A needs to send data to 192.168.1.3. But it must first ask the whole network for the MAC address that responds to 192.168.1.3. When using ARP, host A broadcasts to all hosts the question, "Who has the MAC address for the IP 192.168.1.3?" When host C sees an ARP request for its own IP address, it replies with its MAC address.

Two separate IP networks Consider now another network with 3 hosts, D, E, and F, with the corresponding IP addresses 192.168.2.1, 192.168.2.2, and 192.168.2.3. This is another /24 network, but it is not in the same range as the network above. All three hosts can reach each other directly (first using ARP to resolve the IP address into a MAC address, and then sending packets to that MAC address). Now we will add host G. This host has two network cards, with one plugged into each network. The

first network card uses the IP address 192.168.1.4, and the other uses 192.168.2.4. Host G is now link-local to both networks, and can route packets between them. But what if hosts A, B, and C want to reach hosts D, E, and F? They will need to add a route to the other network via host G. For example, hosts A-C would add a route via 192.168.1.4. In Linux, this can be accomplished with the following command: # ip route add 192.168.2.0/24 via 192.168.1.4 ...and hosts D-F would add the following: # ip route add 192.168.1.0/24 via 192.168.2.4 The result is shown in Figure below. Notice that the route is added via the IP address on host G that is link-local to the respective network. Host A could not add a route via 192.168.2.4, even though it is the same physical machine as 192.168.1.4 (host G), since that IP is not link-local.

Host G acts as a router between the two networks A route tells the OS that the desired network doesn't lie on the immediate link-local network, and it must forward the traffic through the specified router. If host A wants to send a packet to host F, it would first send it to host G. Host G would then look up host F in its routing table, and see that it has a direct connection to host F's network. Finally, host G would resolve the hardware (MAC) address of host F and forward the packet to it. This is a very simple routing example, where the destination is only a single hop away from the source. As networks get more complex, many hops may need to be traversed to reach the ultimate destination. Since it isn't practical for every machine on the Internet to know the route to every other, we make use of a routing entry known as the default route (also known as the default gateway). When a router receives a packet destined for a network for which it has no explicit route, the packet is forwarded to its default

gateway. The default gateway is typically the best route out of your network, usually in the direction of your ISP. An example of a router that uses a default gateway is shown in Figure below.

When no explicit route exists to a particular destination, a host uses the default gateway entry in its routing table. Routes can be updated manually, or can dynamically react to network outages and other events. Some examples of popular dynamic routing protocols are RIP, OSPF, BGP, and OLSR.

Network Address Translation (NAT) In order to reach hosts on the Internet, RFC1918 addresses must be converted to global, publicly routable IP addresses. This is achieved using a technique known as Network Address Translation, or NAT. A NAT device is a router that manipulates the addresses of packets instead of simply forwarding them. On a NAT router, the Internet connection uses one (or more) globally routed IP addresses, while the private network uses an IP address from the RFC1918 private address range. The NAT router allows the global address (es) to be shared with all of the inside users, who all use private addresses. It converts the packets from one form of addressing to the other as the packets pass through it. As far as the network users can tell, they are directly connected to the Internet and require no special software or drivers. They simply use the NAT router as their default gateway, and address packets as they normally would. The NAT router translates outbound packets to use the global IP address as they leave the network, and translates them back again as they are received from the Internet. The major consequence of using NAT is that machines from the Internet cannot easily reach servers within the organization without setting up explicit forwarding rules on the router. Connections initiated from within the private address space generally have no

trouble, although some applications (such as Voice over IP and some VPN software) can have difficulty dealing with NAT.

Network Address Translation allows you to share a single IP address with many internal hosts, but can make it difficult for some services to work properly. Depending on your point of view, this can be considered a bug (since it makes it harder to set up two-way communication) or a feature (since it effectively provides a "free" firewall for your entire organization). RFC1918 addresses should be filtered on the edge of your network to prevent accidental or malicious RFC1918 traffic entering or leaving your network. While NAT performs some firewall-like functions, it is not a replacement for a real firewall.

Internet Protocol Suite Machines on the Internet use the Internet Protocol (IP) to reach each other, even when separated by many intermediary machines. There are a number of protocols that are run in conjunction with IP that provide features as critical to normal operations as IP itself. Every packet specifies a protocol number which identifies the packet as one of these protocols. The most commonly used protocols are the Transmission Control Protocol (TCP, number 6), User Datagram Protocol (UDP, number 17), and the Internet Control Message Protocol (ICMP, number 1). Taken as a group, these protocols (and others) are known as the Internet Protocol Suite, or simply TCP/IP for short. The TCP and UDP protocols introduce the concept of port numbers. Port numbers allow multiple services to be run on the same IP address, and still be distinguished from each other. Every packet has a source and destination port number. Some port numbers are well defined standards, used to reach well known services such as email and web servers. For example, web servers normally listen on TCP port 80, and SMTP email servers listen on TCP port 25. When we say that a service "listens" on a port (such as port 80), we mean that it will accept packets that use its IP as the destination IP address, and 80 as the destination port. Servers usually do not care about the source IP or source port, although sometimes they will use them to establish the identity of the other side. When sending a response to such packets, the server will use its own IP as the source IP, and 80 as the source port. When a client connects to a service, it may use any source

port number on its side which is not already in use, but it must connect to the proper port on the server (e.g. 80 for web, 25 for email). TCP is a session oriented protocol with guaranteed delivery and transmission control features (such as detection and mitigation of network congestion, retries, packet reordering and reassembly, etc.). UDP is designed for connectionless streams of information, and does not guarantee delivery at all, or in any particular order. The ICMP protocol is designed for debugging and maintenance on the Internet. Rather than port numbers, it has message types, which are also numbers. Different message types are used to request a simple response from another computer (echo request), notify the sender of another packet of a possible routing loop (time exceeded), or inform the sender that a packet that could not be delivered due to firewall rules or other problems (destination unreachable). By now you should have a solid understanding of how computers on the network are addressed, and how information flows on the network between them. Now let's take a brief look at the physical hardware that implements these network protocols.

Ethernet Ethernet is the name of the most popular standard for connecting together computers on a Local Area Network (LAN). It is sometimes used to connect individual computers to the Internet, via a router, ADSL modem, or wireless device. However, if you connect a single computer to the Internet, you may not use Ethernet at all. The name comes from the physical concept of the ether, the medium which was once supposed to carry light waves through free space. The official standard is called IEEE 802.3. The most common Ethernet standard is called 100baseT. This defines a data rate of 100 megabits per second, running over twisted pair wires, with modular RJ45 connectors on the end. The network topology is a star, with switches or hubs at the center of each star, and end nodes (devices and additional switches) at the edges.

MAC addresses Every device connected to an Ethernet network has a unique MAC address, assigned by the manufacturer of the network card. Its function is like that of an IP address, since it serves as a unique identifier that enables devices to talk to each other. However, the scope of a MAC address is limited to a broadcast domain, which is defined as all the computers connected together by wires, hubs, switches, and bridges, but not crossing routers or Internet gateways. MAC addresses are never used directly on the Internet, and are not transmitted across routers.

Hubs Ethernet hubs connect multiple twisted-pair Ethernet devices together. They work at the physical layer (the lowest or first layer). They repeat the signals received by each port out to all of the other ports. Hubs can therefore be considered to be simple repeaters. Due to this design, only one port can successfully transmit at a time. If two devices transmit at the same time, they corrupt each other's transmissions, and both must back off and retransmit their packets later. This is known as a

collision, and each host remains responsible for detecting collisions during transmission, and retransmitting its own packets when needed. When problems such as excessive collisions are detected on a port, some hubs can disconnect (partition) that port for a while to limit its impact on the rest of the network. While a port is partitioned, devices attached to it cannot communicate with the rest of the network. Hub-based networks are generally more robust than coaxial Ethernet (also known as 10base2 or ThinNet), where misbehaving devices can disable the entire segment. But hubs are limited in their usefulness, since they can easily become points of congestion on busy networks.

Switches A switch is a device which operates much like a hub, but provides a dedicated (or switched) connection between ports. Rather than repeating all traffic on every port, the switch determines which ports are communicating directly and temporarily connects them together. Switches generally provide much better performance than hubs, especially on busy networks with many computers. They are not much more expensive than hubs, and are replacing them in many situations. Switches work at the data link layer (the second layer); since they interpret and act upon the MAC address in the packets they receive. When a packet arrives at a port on a switch, it makes a note of the source MAC address, which it associates with that port. It stores this information in an internal MAC table. The switch then looks up the destination MAC address in its MAC table, and transmits the packet on the matching port. If the destination MAC address is not found in the MAC table, the packet is then sent to all of the connected interfaces. If the destination port matches the incoming port, the packet is filtered and is not forwarded.

Hubs vs. Switches Hubs are considered to be fairly unsophisticated devices, since they inefficiently rebroadcast all traffic on every port. This simplicity introduces both a performance penalty and a security issue. Overall performance is slower, since the available bandwidth must be shared between all ports. Since all traffic is seen by all ports, any host on the network can easily monitor all of the network traffic. Switches create virtual connections between receiving and transmitting ports. This yields better performance because many virtual connections can be made simultaneously. More expensive switches can switch traffic by inspecting packets at higher levels (at the transport or application layer), allow the creation of VLANs, and implement other advanced features. A hub can be used when repetition of traffic on all ports is desirable; for example, when you want to explicitly allow a monitoring machine to see all of the traffic on the network. Most switches provide monitor port functionality that enables repeating on an assigned port specifically for this purpose. Hubs were once cheaper than switches. However, the price of switches have reduced dramatically over the years. Therefore, old network hubs should be replaced whenever possible with new switches.

A hub simply repeats all traffic on every port, while a switch makes a temporary, dedicated connection between the ports that need to communicate. Both hubs and switches may offer managed services. Some of these services include the ability to set the link speed (10baseT, 100baseT, 1000baseT, full or half duplex) per port, enable triggers to watch for network events (such as changes in MAC address or malformed packets), and usually include port counters for easy bandwidth accounting. A managed switch that provides upload and download byte counts for every physical port can greatly simplify network monitoring. These services are typically available via SNMP, or they may be accessed via telnet, ssh, a web interface, or a custom configuration tool. Routers and firewalls While hubs and switches provide connectivity on a local network segment, a router's job is to forward packets between different network segments. A router typically has two or more physical network interfaces. It may include support for different types of network media, such as Ethernet, ATM, DSL, or dial-up. Routers can be dedicated hardware devices (such as Cisco or Juniper routers) or they can be made from a standard PC with multiple network cards and appropriate software. Routers sit at the edge of two or more networks. By definition, they have one connection to each network, and as border machines they may take on other responsibilities as well as routing. Many routers have firewall capabilities that provide a mechanism to filter or redirect packets that do not fit security or access policy requirements. They may also provide Network Address Translation (NAT) services. Routers vary widely in cost and capabilities. The lowest cost and least flexible are simple, dedicated hardware devices, often with NAT functionality, used to share an Internet connection between a few computers. The next step up is a software router, which consists of an operating system running on a standard PC with multiple network interfaces. Standard operating systems such as Microsoft Windows, Linux, and BSD are all capable of routing, and are much more flexible than the low-cost hardware devices. However, they suffer from the same problems as conventional PCs, with high power consumption, a large number of complex and potentially unreliable parts, and more involved configuration. The most expensive devices are high-end dedicated hardware routers, made by companies like Cisco and Juniper. They tend to have much better performance, more features, and higher

reliability than software routers on PCs. It is also possible to purchase technical support and maintenance contracts for them.Most modern routers offer mechanisms to monitor and record performance remotely, usually via the Simple Network Management Protocol (SNMP), although the least expensive devices often omit this feature.

Other equipment

Many DSL modems, cable modems, CSU/DSUs, wireless access points,and VSAT terminals terminate at an Ethernet jack. Each physical network has an associated piece of terminal equipment. For example, VSAT connections consist of a satellite dish connected to a terminal that either plugs into a card inside a PC, or ends at a standard Ethernet connection. DSL lines use a DSL modem that bridges the telephone line to a local device, either an Ethernet network or a single computer via USB. Cable modems bridge the television cable to Ethernet, or to an internal PC card bus. Some kinds of telecom circuit (such as a T1 or T3) use a CSU/DSU to bridge the circuit to a serial port or Ethernet. Standard dialup lines use modems to connect a computer to the telephone, usually via a plug-in card or serial port. And there are many different kinds of wireless networking equipment that connect to a variety of radios and antennas, but nearly always end at an Ethernet jack. The functionality of these devices can vary significantly between manufacturers. Some provide mechanisms for monitoring performance, while others may not. Since your Internet connection ultimately comes from your ISP, you should follow their recommendations when choosing equipment that bridges their network to your Ethernet network.

Putting it all together

Internet networking. Each network segment has a router with two IP addresses, making it link local to two different networks. Packets are forwarded between routers until they reach their ultimate destination. Once all network nodes have an IP address, they can send data packets to the IP address of any other node. Through the use of routing and forwarding, these packets can reach nodes on networks that are not physically connected to the originating node. This process describes much of what happens on the Internet. In this example, you can see the path that the packets take as Alice chats with Bob using an instant messaging service. Each dotted line represents an Ethernet cable, a wireless link, or any other kind of physical network. The cloud symbol is commonly used to stand in for The Internet, and represents any number of intervening IP networks. Neither Alice nor Bob need to be concerned with how those networks operate, as long as the routers forward IP traffic towards the ultimate destination. If it were not for Internet protocols and the cooperation of everyone on the net, this kind of communication would be impossible.

Designing the physical network It may seem odd to talk about the physical network when building wireless networks. After all, where is the physical part of the network? In wireless networks, the physical medium we use for communication is obviously electromagnetic energy. But in the context of this chapter, the physical network refers to the mundane topic of where to put things. How do you arrange the equipment so that you can reach your wireless clients? Whether they fill an office building or stretch across many miles, wireless networks are naturally arranged in these three logical configurations: point-to-point links, point to multipoint links, and multipoint-to-multipoint

clouds. While different parts of your network can take advantage of all three of these configurations, any individual link will fall into one of these topologies. Point-to-point Point-to-point links typically provide an Internet connection where such access isnt otherwise available. One side of a point-to-point link will have an Internet connection, while the other uses the link to reach the Internet. For example, a university may have a fast frame relay or VSAT connection in the middle of campus, but cannot afford such a connection for an important building just off campus. If the main building has an unobstructed view of the remote site, a point-to-point connection can be used to link the two together. This can augment or even replace existing dial-up links. With proper antennas and clear line of sight, reliable point-to-point links in excess of thirty kilometers are possible.

A point-to-point link allows a remote site to share a central Internet connection. Of course, once a single point-to-point connection has been made, more can be used to extend the network even further. If the remote building in our example is at the top of a tall hill, it may be able to see other important locations that cant be seen directly from the central campus. By installing another point-to-point link at the remote site, another node can join the network and make use of the central Internet connection. Point-to-point links dont necessarily have to involve Internet access. Suppose you have to physically drive to a remote weather monitoring station, high in the hills, in order to collect the data which it records over time. You could connect the site with a point-to-point link, allowing data collection and monitoring to happen in realtime, without the need to actually travel to the site. Wireless networks can provide enough bandwidth to carry large amounts of data (including audio and video) between any two points that have a connection to each other, even if there is no direct connection to the Internet.

Point-to-multipoint The next most commonly encountered network layout is point to multipoint. Whenever several nodes2 are talking to a central point of access, this is a point-to-multipoint application. The typical example of a point-to multipoint layout is the use of a wireless access point that provides a connection to several laptops. The laptops do not communicate with each other directly, but must be in range of the access point in order to use the network.

The central VSAT is now shared by multiple remote sites. All three sites can also communicate directly at speeds much faster than VSAT. Point-to-multipoint networking can also apply to our earlier example at the university. Suppose the remote building on top of the hill is connected to the central campus with a point-to-point link. Rather than setting up several point-to-point links to distribute the Internet connection, a single antenna could be used that is visible from several remote buildings. This is a classic example of a wide area point (remote site on the hill) to multipoint (many buildings in the valley below) connection. Note that there are a number of performance issues with using point-to multipoint over very long distance, which will be addressed later in this chapter. Such links are possible and useful in many circumstances, but dont make the classic mistake of installing a single high powered radio tower in the middle of town and expecting to be able to serve thousands of clients, as you would with an FM radio station. As we will see, two-way data networks behave very differently than broadcast radio. Note: A node is any device capable of sending and receiving data on a network. Access points, routers, computers, and laptops are all examples of nodes.

Multipoint-to-multipoint The third type of network layout is multipoint-to-multipoint, which is also referred to as an adhoc or mesh network. In a multipoint-to-multipoint network, there is no central authority. Every node on the network carries the traffic of every other as needed, and all nodes communicate with each other directly.

A multipoint-to-multipoint mesh. Every point can reach each other at very high speed, or use the central VSAT connection to reach the Internet.

The benefit of this network layout is that even if none of the nodes are in range of a central access point, they can still communicate with each other. Good mesh network implementations are self-healing, which means that they automatically detect routing problems and fix them as needed. Extending a mesh network is as simple as adding more nodes. If one of the nodes in the "cloud" happens to be an Internet gateway, then that connection can be shared among all of the clients. Two big disadvantages to this topology are increased complexity and lower performance. Security in such a network is also a concern, since every participant potentially carries the traffic of every other. Multipoint-to-multipoint networks tend to be difficult to troubleshoot, due to the large number of changing variables as nodes join and leave the network. Multipoint-to multipoint clouds typically have reduce capacity compared to point-to-point or point-to-multipoint networks, due to the additional overhead of managing the network routing and increased contention in the radio spectrum. Nevertheless, mesh networks are useful in many circumstances. We will see an example of how to build a multipoint-to-multipoint mesh network using a routing protocol called OLSR later in this chapter.

Use the technology that fits All of these network designs can be used to complement each other in a large network, and can obviously make use of traditional wired networking techniques whenever possible. It is a common practice, for example, to use a long distance wireless link to provide Internet access to a remote location, and then set up an access point on the remote side to provide local wireless access. One of the clients of this access point may also act as a mesh node, allowing the network to spread organically between laptop users who all ultimately use the original point-to-point link to access the Internet. Now that we have a clear idea of how wireless networks are typically arranged, we can begin to understand how communication is possible over such networks.

802.11 wireless networks Before packets can be forwarded and routed to the Internet, layers one (the physical) and two (the data link) need to be connected. Without link local connectivity, network nodes cannot talk to each other and route packets. To provide physical connectivity, wireless network devices must operate in the same part of the radio spectrum. As we know , this means that 802.11a radios will talk to 802.11a radios at around 5 GHz, and 802.11b/g radios will talk to other 802.11b/g radios at around 2.4GHz. But an 802.11a device cannot interoperate with an 802.11b/g device, since they use completely different parts of the electromagnetic spectrum. More specifically, wireless cards must agree on a common channel. If one 802.11b radio card is set to channel 2 while another is set to channel 11, then the radios cannot communicate with each other.

When two wireless cards are configured to use the same protocol on the same radio channel, then they are ready to negotiate data link layer connectivity. Each 802.11a/b/g device can operate in one of four possible modes: 1. Master mode (also called AP or infrastructure mode) is used to create a service that looks like a traditional access point. The wireless card creates a network with a specified name (called the SSID) and channel, and offers network services on it. While in master mode, wireless cards manage all communications related to the network (authenticating wireless clients, handling channel contention, repeating packets, etc.) Wireless cards in master mode can only communicate with cards that are associated with it in managed mode. 2. Managed mode is sometimes also referred to as client mode. Wireless cards in managed mode will join a network created by a master, and will automatically change their channel to match it. They then present any necessary credentials to the master, and if those credentials are accepted, they are said to be associated with the master. Managed mode cards do not communicate with each other directly, and will only communicate with an associated master. 3. Ad-hoc mode creates a multipoint-to-multipoint network where there is no single master node or AP. In ad-hoc mode, each wireless card communicates directly with its neighbors. Nodes must be in range of each other to communicate, and must agree on a network name and channel. 4. Monitor mode is used by some tools (such as Kismet) to passively listen to all radio traffic on a given channel. When in monitor mode, wireless cards transmit no data. This is useful for analyzing problems on a wireless link or observing spectrum usage in the local area. Monitor mode is not used for normal communications.

APs, Clients, and Ad-Hoc nodes

When implementing a point-to-point or point-to-multipoint link, one radio will typically operate in master mode, while the other(s) operate in managed mode. In a multipoint-to-multipoint mesh, the radios all operate in ad-hoc mode so that they can communicate with each other directly. It is important to keep these modes in mind when designing your network layout. Remember that managed mode clients cannot communicate with each other directly, so it is likely that you will want to run a high repeater site in master or ad-hoc mode. As we will see later in this chapter, adhoc is more flexible but has a number of performance issues as compared to using the master / managed modes.

Wireless mesh network


A wireless mesh network (WMN) is a communications network made up of radio nodes organized in a mesh topology. Wireless mesh networks often consist of mesh clients, mesh routers and gateways. The mesh clients are often laptops, cell phones and other wireless devices while the mesh routers forward traffic to and from the gateways which may but need not connect to the Internet. The coverage area of the radio nodes working as a single network is sometimes called a mesh cloud. Access to this mesh cloud is dependent on the radio nodes working in harmony with each other to create a radio network. A mesh network is reliable and offers redundancy. When one node can no longer operate, the rest of the nodes can still communicate with each other, directly or through one or more intermediate nodes. The animation below illustrates how wireless mesh networks can self form and self heal. Wireless mesh networks can be implemented with various wireless technology including 802.11, 802.15, 802.16, cellular technologies or combinations of more than one type. A wireless mesh network can be seen as a special type of wireless ad-hoc network. A wireless mesh network often has a more planned configuration, and may be deployed to provide dynamic and cost effective connectivity over a certain geographic area. An ad-hoc network, on the other hand, is formed ad hoc when wireless devices come within communication range of each other. The mesh routers may be mobile, and be moved according to specific demands arising in the network. Often the mesh routers are not limited in terms of resources compared to other nodes in the network and thus can be exploited to perform more resource intensive functions. In this way, the wireless mesh network differs from an ad-hoc network, since these nodes are often constrained by resources.

Architecture Wireless mesh architecture is a first step towards providing cost effective and dynamic highbandwidth networks over a specific coverage area. Wireless mesh architectures infrastructure is, in effect, a router network minus the cabling between nodes. It's built of peer radio devices that

don't have to be cabled to a wired port like traditional WLAN access points (AP) do. Mesh architecture sustains signal strength by breaking long distances into a series of shorter hops. Intermediate nodes not only boost the signal, but cooperatively make forwarding decisions based on their knowledge of the network, i.e. perform routing. Such architecture may with careful design provide high bandwidth, spectral efficiency, and economic advantage over the coverage area. Wireless mesh networks have a relatively stable topology except for the occasional failure of nodes or addition of new nodes. The path of traffic, being aggregated from a large number of end users, changes infrequently. Practically all the traffic in an infrastructure mesh network is either forwarded to or from a gateway, while in ad hoc networks or client mesh networks the traffic flows between arbitrary pairs of nodes

Management This type of infrastructure can be decentralized (with no central server) or centrally managed (with a central server), both are relatively inexpensive, and very reliable and resilient, as each node needs only transmit as far as the next node. Nodes act as routers to transmit data from nearby nodes to peers that are too far away to reach in a single hop, resulting in a network that can span larger distances. The topology of a mesh network is also reliable, as each node is connected to several other nodes. If one node drops out of the network, due to hardware failure or any other reason, its neighbors can quickly find another route using a routing protocol.

Applications Mesh networks may involve either fixed or mobile devices. The solutions are as diverse as communication needs, for example in difficult environments such as emergency situations, tunnels, oil rigs, battlefield surveillance, high speed mobile video applications on board public transport or real time racing car telemetry. An important possible application for wireless mesh networks is VoIP. By using a Quality of Service scheme, the wireless mesh may support local telephone calls to be routed through the mesh.

Some current applications:


U.S. military forces are now using wireless mesh networking to connect their computers, mainly ruggedized laptops, in field operations. Electric meters now being deployed on residences transfer their readings from one to another and eventually to the central office for billing without the need for human meter readers or the need to connect the meters with cables.

The laptops in the One Laptop per Child program use wireless mesh networking to enable students to exchange files and get on the Internet even though they lack wired or cell phone or other physical connections in their area. The 66-satellite Iridium constellation operates as a mesh network, with wireless links between adjacent satellites. Calls between two satellite phones are routed through the mesh, from one satellite to another across the constellation, without having to go through an earth station. This makes for a smaller travel distance for the signal, reducing latency, and also allows for the constellation to operate with far fewer earth stations that would be required for 66 traditional communications satellites. The Commotion Wireless Project proposes building a 'device-as-infrastructure' distribution encrypted communications platform

Operation The principle is similar to the way packets travel around the wired Internet data will hop from one device to another until it reaches its destination. Dynamic routing algorithms implemented in each device allow this to happen. To implement such dynamic routing protocols, each device needs to communicate routing information to other devices in the network. Each device then determines what to do with the data it receives either pass it on to the next device or keep it, depending on the protocol. The routing algorithm used should attempt to always ensure that the data takes the most appropriate (fastest) route to its destination.

Multi-radio mesh Multi-radio mesh refers to a unique pair of dedicated radios on each end of the link. This means there is a unique frequency used for each wireless hop and thus a dedicated CSMA collision domain. This is a true mesh link where you can achieve maximum performance without bandwidth degradation in the mesh and without adding latency. Thus voice and video applications work just as they would on a wired Ethernet network. In true 802.11 networks, there is no concept of a mesh. There are only Access Points (AP's) and Stations. A multi-radio wireless mesh node will dedicate one of the radios to act as a station, and connect to a neighbor node AP radio.

Research topics One of the more often cited papers on Wireless Mesh Networks identified the following areas as open research problems in 2005

New modulation scheme

In order to achieve higher transmission rate, new wideband transmission schemes other than OFDM and UWB are needed.

Advanced antenna processing o Advanced antenna processing including directional, smart and multiple antenna technologies is further investigated, since their complexity and cost are still too high for wide commercialization. Flexible spectrum management o Tremendous efforts on research of frequency-agile techniques are being performed for increased efficiency. Cross-layer design o Cross-layer research is a popular current research topic where information is shared between different communications layers in order to increase the knowledge and current state of the network. This could enable new and more efficient protocols to be developed. A joint protocol which combines various design problems like routing, scheduling, channel assignment etc. can achieve higher performance since it is proven that these problems are strongly co-related. It is important to note that careless crosslayer design could lead to code which is difficult to maintain and extend.

Routing protocols There are more than 70 competing schemes for routing packets across mesh networks. Some of these include:

AODV (Ad hoc On-Demand Distance Vector) B.A.T.M.A.N. (Better Approach To Mobile Adhoc Networking) Babel (protocol) (a distance-vector routing protocol for IPv6 and IPv4 with fast convergence properties) DNVR (Dynamic NIx-Vector Routing) DSDV (Destination-Sequenced Distance-Vector Routing) DSR (Dynamic Source Routing) HSLS (Hazy-Sighted Link State) HWMP (Hybrid Wireless Mesh Protocol) IWMP (Infrastructure Wireless Mesh Protocol) for Infrastructure Mesh Networks by GRECO UFPB-Brazil MRP (Wireless mesh networks routing protocol) by Jangeun Jun and Mihail L. Sichitiu OLSR (Optimized Link State Routing protocol) OORP (OrderOne Routing Protocol) (OrderOne Networks Routing Protocol) OSPF (Open Shortest Path First Routing) PWRP (Predictive Wireless Routing Protocol) TORA (Temporally-Ordered Routing Algorithm)

The IEEE is developing a set of standards under the title 802.11s to define an architecture and protocol for ESS Mesh Networking. A more thorough list can be found at Ad hoc routing protocol list: http://en.wikipedia.org/wiki/Ad_hoc_routing_protocol_list

Autoconfiguration protocols Standard autoconfiguration protocols, such as DHCP or IPv6 stateless autoconfiguration may be used over mesh networks. Mesh network specific autoconfiguration protocols include:

Ad-Hoc Configuration Protocol (AHCP) Proactive Autoconfiguration (Proactive Autoconfiguration Protocol) Dynamic WMN Configuration Protocol (DWCP)

IEEE 802.11s: Wireless mesh technology Wireless mesh technology enables 802.11 wireless networks to cover areas far beyond the limits imposed by traditional WLAN technology. Proprietary solutions have been offered for years, but the IEEE 802.11s standard, currently under development, will make multi-vendor mesh networks possible. Most existing 802.11 networks operate in infrastructure mode. All communication travels through an access point (AP) before being forwarded to its final destination. The 802.11 standard also defines ad hoc mode. An ad hoc network has no AP. Stations communicate directly from one to another. 802.11s extends the ad hoc concept. Packets may travel through intermediate stations on the way to their ultimate destination. The result: 802.11 mesh networks can extend across a larger area than non-mesh 802.11. A station can communicate with a station too far away for direct transmission. Packets travel hop by hop via intermediate stations until close enough to the destination for the final transmission. An 802.11s network can operate using any of the 802.11a, b, g or n standards. The Media Access Control (MAC) layer and packet formats have been designed to prevent interference with nonmesh networks so mesh and non-mesh networks can be co-located. No modification of traditional 802.11 equipment is required to enable co-location. All 802.11s functions operate at either the MAC or Link Layer. None of the higher layers of the IP network stack are modified, so applications do not require modification.

Mesh terminology: it defines three kinds of nodes Mesh Point (MP): A 802.11s station supporting node-to-node communication with other 802.11s stations. A Mesh Point (MP) supports a Peer Link Management protocol, which is used to discover neighboring nodes and keep track of them. Note that neighbor discovery is only limited to nodes which are in range of an MP. For communicating with nodes that are farther than one hop, an MP also supports Hybrid Wireless Mesh Protocol (HWMP). It is hybrid, because it supports two kinds of path selection protocols. Although these protocols are very similar to routing protocols, but bear in mind, that in case of IEEE 802.11s these use MAC addresses for "routing", instead of IP addresses. Therefore, we use the term "path" instead of "route" and thus path selection instead of routing. Mesh Portal (MPP): An 802.11s station with a wired network interface in addition to its 802.11s capabilities. It provides a path for packets from the mesh to a wired network. An IEEE 802.11s mesh network could be used for a variety of purposes. One of them is providing cheap Internet access. In this case, at least one node and potentially some of the nodes are connected to the Internet. Users connected to the mesh network can access the Internet via these gateway nodes called Mesh Portals (MPP) which are connected to both the mesh network and the Internet. Note that an MPP must bridge at least two interfaces to provide the gateway functionality.

Mesh Access Point (MAP): A MAP acts as an access point for non-mesh nodes. It may also connect to a wired network and act as an MPP.

Mesh configurations A network can be made up of just MPs communicating among themselves, with no connection to a wired network. A more useful configuration contains an MPP. MPs could be spread out over a large area, possibly outdoors or in a large facility such as a warehouse. Use of conventional nonmesh stations would require locating APs throughout the area and extending the wired network to each. 802.11s requires a single wired connection to an MPP. Distant mesh stations communicate to the MPP via intermediate stations. In another possible configuration, MAPs could be used to provide access across a large area to non-mesh 802.11 stations. Each non-mesh station would associate with the nearest MAP. Packets would then travel hop by hop through intermediately placed MPs to an MPP at the edge of the network. A single wired connection to the MPP could support non-mesh stations too far from the wired connection for a standard AP.

Finding a route through the network To the upper layers of the IP stack, Layer 3 and above, the mesh appears to be a single switched network. 802.11s replaces the spanning tree used in traditional switched networks with Hybrid Wireless Mesh Protocol (HWMP). HWMP creates routes through the mesh using two techniques: proactive routing and on-demand routing.

Proactive routing provides an efficient routing method based on the fact that most mesh networks will include at least one Mesh Portal, and many packets will be routed through a portal. An MP can be configured to be a network root. An MP configured as a root sends periodic Portal Announcements and waits to hear announcements from other MPs. If there are multiple MPs configured to be a root, they negotiate to designate one as the network root. The selected root portal then sends Root Announcements that are forwarded hop by hop through the network. Each MP creates a tree-structured routing table based on received Root Announcements from neighboring MPs. An MP will often receive multiple announcements that have traveled different paths. It will create a routing table based on metrics in the announcement that are updated by each MP along the path. 802.11s nodes use on-demand routing to find destination nodes when there is no proactive route to the destination. The source node sends requests for the destination to neighboring nodes. The requests are forwarded along until one reaches the destination. The destination node then sends a response that is forwarded back to the source. Requests are sent to all neighboring nodes and may travel many paths to the destination. Duplicate copies may arrive at the destination node. Similarly, duplicate copies of the response may be received by the initial sending node. Radio Metric Ad Hoc On Demand Distance Vector routing (RM-AODV) is used to choose among the possible paths. RM-AODV is a modified version of AODV, enhanced to include airtime, a metric based on observed transmission rate, amount of traffic and interference along a path. Note: an MPP must bridge at least two interfaces to provide the gateway functionality. Information Elements IEEE 802.11 support Information Elements (IE) contained in beacon or probe response frames. There are multiple kinds of IEs. In the context of IEEE 802.11s, following IEs are used

Mesh Configuration Peer Link Information Element Path Request (PREQ), Path Reply (PREP), Path Error(PERR), Root Annoucement (RANN) { Specific to HWMP }

The above list might not be complete and other IEs specific to IEEE 802.11s can be added above.

Network Formation The iw utility can be used to configure a node as an MP. Configuration includes setting the mesh ID (similar to SSID in infrastructure-based (AP) networks) and channel at the least. Other things that are included in the configuration are described by the Mesh Configuration Information Element. Once a node is configured as an MP, it starts sending out beacons at regular intervals

(by default every second). These beacons contain the Mesh Configuration IE mentioned above. This information element has following fields

Path Selection Protocol ID Path Selection metric Congestion Control Mode Synchronization Protocol ID Authentication Protocol ID Mesh Formation Info (Usually the count of neighbors/peers) Mesh Capability (includes whether this node allows establishment of peer links)

In case of mac80211, the mesh interface is represented by struct ieee80211_if_mesh shown below: 1 struct ieee80211_if_mesh { 2 struct work_struct work; 3 struct timer_list housekeeping_timer; 4 struct timer_list mesh_path_timer; 5 struct timer_list mesh_path_root_timer; 6 struct sk_buff_head skb_queue; 7 8 unsigned long timers_running; 9 10 unsigned long wrkq_flags; 11 12 u8 mesh_id[IEEE11_MAX_MESH_ID_LEN]; 13 size_t mesh_id_len; 14 /* Active Path Selection Protocol Identifier */ 15 u8 mesh_pp_id; 16 /* Active Path Selection Metric Identifier */ 17 u8 mesh_pm_id; 18 /* Congestion Control Mode Identifier */ 19 u8 mesh_cc_id; 20 /* Synchronization Protocol Identifier */ 21 u8 mesh_sp_id; 22 /* Authentication Protocol Identifier */ 23 u8 mesh_auth_id; 24 /* Local mesh Sequence Number */ 25 u32 sn; 26 /* Last used PREQ ID */ 27 u32 preq_id; 28 atomic_t mpaths; 29 /* Timestamp of last SN update */ 30 unsigned long last_sn_update; 31 /* Timestamp of last SN sent */ 32 unsigned long last_preq;

33 34 35 36 37 38 39 40 41 };

struct mesh_rmc *rmc; spinlock_t mesh_preq_queue_lock; struct mesh_preq_queue preq_queue; int preq_queue_len; struct mesh_stats mshstats; struct mesh_config mshcfg; u32 mesh_seqnum; bool accepting_plinks;

The above structure maintains state information regarding a mesh interface. The current configuration of a mesh interface is stored in this interface. The Mesh Configuration IE is important because, a node that receives a beacon from an existing node, should only process it, if it is configured to connect to the same network or is already part of the network having the same configuration as specified by the Mesh Configuration IE. This check is performed by the function mesh_matches_local. A new node that wishes to be a part of the mesh network must be configured with the correct mesh ID and must be set to the correct channel. Once that is done, the new node will also start sending beacons. At this point, two things will happen. The node that started the network, will receive beacons from the new node, and the new node will also start receiving beacons from the existing node(s). On receiving the beacons, both nodes will start the Peer Link Management protocol, which is basically a four-way handshake. After the completion of handshake, each node will add the other in its station hash (read neighbor table). The following ASCII diagram describes the ideal (without loss) four-way handshake. Here, P2 is an existing node in a mesh network, and P1 is a node which receives the beacon or probe response from P2. P1 might be a new node joining the network or it might have lost the connection (because of moving away/crash) and can now listen to P2's beacons again because it recovered or the link became active again. Beacon/Probe resp P1's state <-------------P2's state PLINK_LISTEN PLINK_LISTEN PLINK_OPEN PLINK_OPN_SNT --------------> PLINK_OPN_RCVD PLINK_OPEN PLINK_OPN_RCVD <-------------PLINK_CONFIRM PLINK_ESTAB <-------------PLINK_OPN_RCVD

PLINK_OPN_RCVD

PLINK_CONFIRM PLINK_ESTAB ---------------> PLINK_ESTAB

All peer link management frames are IEEE 802.11 frames of type management and the sub-type is action. The function that is called to process IEEE 802.11s (mesh) management frames of type action is ieee80211_mesh_rx_queued_mgmt (invoked by ieee80211_iface_work which is the interface workqueue function). Following shows an excerpt from this function: switch (stype) { case IEEE80211_STYPE_PROBE_RESP: case IEEE80211_STYPE_BEACON: ieee80211_mesh_rx_bcn_presp(sdata, stype, mgmt, skb->len, rx_status); break; case IEEE80211_STYPE_ACTION: ieee80211_mesh_rx_mgmt_action(sdata, mgmt, skb->len, rx_status); break; } stype in the above code refers to subtype of the received IEEE 802.11 frame. You can dig it up further to find more information about the peer link management state machine. Note that, HWMP frames are also management frames with subtype action, so you will find info about that in ieee80211_mesh_rx_mgmt as well. The on-demand part of HWMP is very similar to AODV, so I will recommend reading about AODV from the web in order to gain familiarity with the code.

Wireless security with 802.11s Mesh networks add complexity to the process of establishing secure access because nodes maintain paths to many neighboring nodes, not just to a single AP. 802.11s uses the 802.11i and 802.1X standards. Each node uses 802.11i to negotiate parameters and key pairs with each adjacent node. While the 802.11s standard is not final, implementations are under way. The low-power features in the draft are ideal for the environments in which the One Laptop Per Child (OLPC) organization expects its units to operate. OLPC has developed an implementation for laptop-tolaptop communication based on the draft. Also, the open80211s Consortium is creating an open source implementation. http://www.open80211s.org/index.html

Mesh networking with OLSR


Mesh networking is used to route data, voice and instructions between nodes (typically routers). A mesh network typically consists of 2 or (many) more nodes, which exchange information about their connection-status with each other (routing updates), so that every node knows, which path he has to take to reach any other node in the mesh. When a node wants to reach another node that is not directly connected, the traffic flows over other nodes, until the final node is reached (hopping) -each node that the traffic flows through is called a hop. Most WiFi networks operate in infrastructure mode - they consist of an access point somewhere (with a radio operating in master mode), attached to a DSL line or other large scale wired network. In such a hotspot the access point usually acts as a master station that is distributing Internet access to its clients, which operate in managed mode. This topology is similar to a mobile phone (GSM) service. Mobile phones connect to a base station - without the presence of such a base station mobiles can't communicate with each other. If you make a joke call to a friend that is sitting on the other side of the table, your phone sends data to the base station of your provider that may be a mile away the base station then sends data back to the phone of your friend. WiFi cards in managed mode can't communicate directly, either. Clients for example, two laptops on the same table - have to use the access point as a relay. Any traffic between clients connected to an access point has to be sent twice. If client A and C communicate, client A sends data to the access point B, and then the access point will retransmit the data to client C. A single transmission may have a speed of 600 kByte/sec (thats about the maximum speed you could achieve with 802.11b) in our example - thus, because the data has to be repeated by the access point before it reaches its target, the effective speed between both clients will be only 300 kByte/sec. In ad-hoc mode there is no hierarchical master-client relationship. Nodes can communicate directly as long as they are within the range of their wireless interfaces. Thus, in our example both computers could achieve full speed when operating ad-hoc, under ideal circumstances. The disadvantage to ad-hoc mode is that clients do not repeat traffic destined for other clients. In the access point example, if two clients A and C can't directly see each other with their wireless interfaces, they still can communicate as long as the AP is in the wireless range of both clients. Ad-hoc nodes do not repeat by default, but they can effectively do the same if routing is applied. Mesh networks are based on the strategy that every mesh-enabled node acts as a relay to extend coverage of the wireless network. The more nodes, the better the radio coverage and range of the mesh cloud. Clients A and C are in range of Access Point B but not each other.Access Point B will relay traffic between the two nodes.

In the same setting, Ad-Hoc nodes A and C can communicatewith node B, but not with each other.

Access point B will relay traffic between clients A and C. In Ad-Hocmode, node B will not relay traffic between A and C by default. There is one big tradeoff that must be mentioned at this point. If the device only uses one radio interface, the available bandwidth is significantly reduced every time traffic is repeated by intermediate nodes on the way from A to B. Also, there will be interference in transmission due to nodes sharing the same channel. Thus, cheap ad-hoc mesh networks can provide good radio coverage on the last mile(s) of a community wireless network at the cost of speed-- especially if the density of nodes and transmit power is high. If an ad-hoc network consists of only a few nodes that are up and running at all time, don't move and always have stable radio links - a long list of ifs - it is possible to write individual routing tables for all nodes by hand. Unfortunately, those conditions are rarely met in the real world. Nodes can fail, Wi-Fi enabled devices roam around, and interference can make radio links unusable at any time. And no one wants to update several routing tables by hand if one node is added to the network. By using routing protocols that automatically maintain individual routing tables in all nodes involved, we can avoid these issues. Popular routing protocols from the wired world (such as OSPF) do not work well in such an environment because they are not designed to deal with lossy links or rapidly changing topology. In brief: Mesh networks differ from other networks in that the component parts can all connect to each other via multiple hops. Mesh networks are self-healing: the network can still operate even when a node goes down or a connection drops. The result is a very reliable network.

Benefits of mesh networking


self organizing self-healing low system maintenance needed robust due dynamic route recalculation

Disadvantages of mesh networking Additional network traffic: The exchange of routing information (routing updates) can produce a lot of traffic-overhead, also every device that takes part of a mesh must have enough cpu/ memory to have an overview of all other routers and how to reach them. (routing table). A full routing table can get very large - as seen in BGP-Routing: a full BGP table needs 2GB of memory (300.000 active routes). There is also a danger of routing-loops that can appear because of weak routing information

Mesh routing with olsrd The Optimized Link State Routing Daemon - olsrd - from www.olsr.org is a routing application developed for routing in wireless networks. We will concentrate on this routing software for several reasons. It is a open-source project that supports Mac OS X, Windows 98, 2000, XP, Linux, FreeBSD, OpenBSD and NetBSD. Olsrd is available for access points that run Linux like the Linksys WRT54G, Asus Wl500g, AccessCube or Pocket PCs running Familiar Linux, and ships standard on Metrix kits running Pyramid. Olsrd can handle multiple interfaces and is extensible with plug-ins. It supports IPv6 and it is actively developed and used by community networks all over the world. Note that there are several implementations of Optimized Link State Routing, which began as an IETF-draft written at INRIA France. The implementation from olsr.org started as a master thesis of Andreas Toennesen at UniK University. Based on practical experience of the free networking community, the routing daemon was modified. Olsrd now differs significantly from the original draft because it includes a mechanism called Link Quality Extension that measures the packet loss between nodes and calculates routes according to this information. This extension breaks compatibility to routing daemons that follow the INRIA draft. The olsrd available from olsr.org can be configured to behave according to the IETF draft that lacks this feature - but there is no reason to disable Link Quality Extension unless compliance with other implementations is required.

Theory After olsrd is running for a while, a node knows about the existence ofevery other node in the mesh cloud and which nodes may be used to route traffic to them. Each node maintains a routing table covering the whole mesh cloud. This approach to mesh routing is called proactive routing. In contrast, reactive routing algorithms seek routes only when it is necessary to send data to a specific node. There are pros and cons to proactive routing, and there are many other ideas about how to do mesh routing that may be worth mentioning. The biggest advantage of proactive routing is that you know who is out there and you don't have to wait until a route is found. Higher protocol traffic overhead and more CPU load are among the disadvantages. In Berlin, the Freifunk community is operating a mesh cloud where olsrd has to manage more than 100 interfaces. The average CPU load caused by olsrd on a Linksys WRT54G running at 200 MHz is about 30% in the Berlin mesh. There is clearly a limit to what extent a proactive protocol can scale - depending on how many interfaces are involved and how often the routing tables are updated. Maintaining routes in a mesh cloud with static nodes takes less effort than a mesh with nodes that are constantly in motion, since the routing table has to be updated less often.

Mechanism A node running olsrd is constantly broadcasting 'Hello' messages at a given interval so neighbors can detect it's presence. Every node computes a statistic how many 'Hellos' have been lost or received from each neighbor thereby gaining information about the topology and link quality of nodes in the neighborhood. The gained topology information is broadcasted as topology control messages (TC messages) and forwarded by neighbors that olsrd has chosen to be multipoint relays. The concept of multipoint relays is a new idea in proactive routing that came up with the OLSR draft. If every node rebroadcasts topology information that it has received, unnecessary overhead can be generated. Such transmissions are redundant if a node has many neighbors. Thus, an olsrd node decides which neighbors are favorable multipoint relays that should forward its topology control messages. Note that multipoint relays are only chosen for the purpose of forwarding TC messages. Payload is routed considering all available nodes. Two other message types exist in OLSR that announce information: whether a node offers a gateway to other networks (HNA messages) or has multiple interfaces (MID messages). There is not much to say about what these messages do apart from the fact that they exist. HNA messages make olsrd very convenient when connecting to the Internet with a mobile device. When a mesh node roams around it will detect gateways into other networks and always choose the gateway that it has the best route to. However, olsrd is by no means bullet proof. If a node announces that it is an Internet gateway which it isn't because it never was or it is just offline at the moment the other nodes will nevertheless trust this information. The pseudo-gateway is a black hole. To overcome this problem, a dynamic gateway plugin was written. The plugin will automatically detect at the gateway if it is actually connected and whether the link is still up. If not, olsrd ceases to send false HNA messages. It is highly recommended to build and use this plugin instead of statically enabling HNA messages.

Practice Olsrd implements IP-based routing in a userland application - installation is pretty easy. Installation packages are available for OpenWRT, AccessCube, Mac OS X, Debian GNU/Linux and Windows. OLSR is a standard part of Metrix Pyramid. If you have to compile from source, please read the documentation that is shipped with the source package. If everything is configured properly all you have to do is start the olsr program. First of all, it must be ensured that every node has a unique statically assigned IP-Address for each interface used for the mesh. It is not recommended (nor practicable) to use DHCP in an IPbased mesh network. A DHCP request will not be answered by a DHCP server if the node requesting DHCP needs a multihop link to connect to it, and applying dhcp relay throughout a mesh is likely impractical. This problem could be solved by using IPv6, since there is plenty of space available to generate a unique IP from the MAC address of each card involved (as suggested in "IPv6 State-less Address Autoconfiguration in large mobile ad hoc networks" by K. Weniger and M. Zitterbart, 2002). A wiki-page where every interested person can choose an individual IPv4 address for each interface the olsr daemon is running on may serve the purpose quite well. There is just not an easy way to automate the process if IPv4 is used. The broadcast address should be 255.255.255.255 on mesh interfaces in general as a convention. There is no reason to enter the broadcast address explicitly, since olsrd can be configured to override the broadcast addresses with this default. It just has to be ensured that settings are the same everywhere. Olsrd can do this on its own. When a default olsrd configuration file is issued, this feature should be enabled to avoid confusion of the kind "why can't the other nodes see my machine?!?" Now configure the wireless interface. Here is an example command how to configure a WiFi card with the name wlan0 using Linux: iwconfig wlan0 essid olsr.org mode ad-hoc channel 10 rts 250 frag 256 Verify that the wireless part of the WiFi card has been configured so it has an ad-hoc connection to other mesh nodes within direct (single hop) range. Make sure the interface joins the same wireless channel, uses the same wireless network name ESSID (Extended Service Set IDentifier) and has the same Cell-ID as all other WiFi-Cards that build the mesh. Many WiFi cards or their respective drivers do not comply with the 802.11 standard for ad-hoc networking and may fail miserably to connect to a cell. They may be unable to connect to other devices on the same table, even if they are set up with the correct channel and wireless network name. They may even confuse other cards that behave according to the standard by creating their own Cell-ID on the same channel with the same wireless network name. Wi-Fi cards made by Intel that are shipped with Centrino Notebooks are notorious for doing this. You can check this out with the command iwconfig when using GNULinux. Here is the output on my machine:

wlan0 IEEE 802.11b ESSID:"olsr.org" Mode:Ad-Hoc Frequency:2.457 GHz Cell: 02:00:81:1E:48:10 Bit Rate:2 Mb/s Sensitivity=1/3 Retry min limit:8 RTS thr=250 B Fragment thr=256 B Encryption key:off Power Management:off Link Quality=1/70 Signal level=-92 dBm Noise level=-100 dBm Rx invalid nwid:0 Rx invalid crypt:28 Rx invalid frag:0 Tx excessive retries:98024 Invalid misc:117503 Missed beacon:0 It is important to set the 'Request To Send' threshold value RTS for a mesh. There will be collisions on the radio channel between the transmissions of nodes on the same wireless channel, and RTS will mitigate this. RTS/CTS adds a handshake before each packet transmission to make sure that the channel is clear. This adds overhead, but increases performance in case of hidden nodes - and hidden nodes are the default in a mesh! This parameter sets the size of the smallest packet (in bytes) for which the node sends RTS. The RTS threshold value must be smaller than the IP-Packet size and the 'Fragmentation threshold' value - here set to 256 - otherwise it will be disabled. TCP is very sensitive to collisions, so it is important to switch RTS on. Fragmentation allows splitting an IP packet in a burst of smaller fragments transmitted on the medium. This adds overhead, but in a noisy environment this reduces the error penalty and allows packets to get through interference bursts. Mesh networks are very noisy because nodes use the same channel and therefore transmissions are likely to interfere with each other. This parameter sets the maximum size before a data packet is split and sent in a burst - a value equal to the maximum IP packet size disables the mechanism, so it must be smaller than the IP packet size. Setting fragmentation threshold is recommended. Once a valid IP-address and netmask is assigned and the wireless interface is up, the configuration file of olsrd must be altered in order that olsrd finds and uses the interfaces it is meant to work on. For Mac OS-X and Windows there are nice GUI's for configuration and monitoring of the daemon available. Unfortunately this tempts users that lack background knowledge to do stupid things - like announcing black holes. On BSD and Linux the configuration file /etc/olsrd.conf has to be edited with a text editor.

A simple olsrd.conf It is not practical to provide a complete configuration file here. These are some essential settings that should be checked.

UseHysteresis no TcRedundancy 2 MprCoverage 3 LinkQualityLevel 2 LinkQualityWinSize 20 LoadPlugin "olsrd_dyn_gw.so.0.3" { PlParam "Interval" "60" PlParam "Ping" "151.1.1.1" PlParam "Ping" "194.25.2.129" } Interface "ath0" "wlan0" { Ip4Broadcast 255.255.255.255 }

There are many more options available in the olsrd.conf, but these basic options should get you started. After these steps have been done, olsrd can be started with a simple command in a terminal:

olsrd -d 2 I recommend to run it with the debugging option -d 2 when used on a workstation, especially for the first time. You can see what olsrd does and monitor how well the links to your neighbors are. On embedded devices the debug level should be 0 (off), because debugging creates a lot of CPU load. The output should look something like this:

--- 19:27:45.51 --------------------------------------------- DIJKSTRA 192.168.120.1:1.00 (one-hop) 192.168.120.3:1.00 (one-hop) --- 19:27:45.51 ------------------------------------------------ LINKS IP address hyst LQ lost total NLQ ETX 192.168.120.1 0.000 1.000 0 20 1.000 1.00 192.168.120.3 0.000 1.000 0 20 1.000 1.00 --- 19:27:45.51 -------------------------------------------- NEIGHBORS IP address LQ NLQ SYM MPR MPRS will 192.168.120.1 1.000 1.000 YES NO YES 3 192.168.120.3 1.000 1.000 YES NO YES 6 --- 19:27:45.51 --------------------------------------------- TOPOLOGY Source IP addr Dest IP addr LQ ILQ ETX 192.168.120.1 192.168.120.17 1.000 1.000 1.00 192.168.120.3 192.168.120.17 1.000 1.000 1.00

Using OLSR on Ethernet and multiple interfaces It is not necessary to have a wireless interface to test or use olsrd although that is what olsrd is designed for. It may as well be used on any NIC. Wi-Fi interfaces don't have to operate always in ad-hoc mode to form a mesh when mesh nodes have more than one interface. For dedicated links it may be a very good option to have them running in infrastructure mode. Many Wi-Fi cards and drivers are buggy in ad-hoc mode, but infrastructure mode works fine - because everybody expects at least this feature to work. Ad-hoc mode has not had many users so far, so the implementation of the ad-hoc mode was done sloppily by many manufacturers. With the rising popularity of mesh networks, the driver situation is improving now. Many people use olsrd on wired and wireless interfaces - they don't think about network architecture. They just connect antennas to their WiFi cards, connect cables to their Ethernet cards, enable olsrd to run on all computers and all interfaces and fire it up. That is quite an abuse of a protocol that was designed to do wireless networking on lossy links - but - why not? They expect olsrd to solve every networking problem. Clearly it is not necessary to send 'Hello' messages on a wired interface every two seconds - but it works. This should not be taken as a recommendation - it is just amazing what people do with such a protocol and that they have such success with it. In fact the idea of having a protocol that does everything for newbies that want to have a small to medium sized routed LAN is very appealing.

Plugins A number of plugins are available for olsrd. Check out the olsr.org website for a complete list. Here a little HOWTO for the network topology visualization plugin olsrd_dot_draw.

An automatically generated OLSR network topology Often it is very good for the understanding of a mesh network to have the ability to show the network topology graphically. olsrd_dot_draw outputs the topology in the dot file format on TCP port 2004. The graphviz tools can then be used to draw the graphs.

Installing the dot_draw Plugin Compile the olsr plugins separately and install them. To load the plugin add the following lines to /etc/olsrd.conf. The parameter "accept" specifies which host is accepted to view the Topology Information (currently only one) and is "localhost" by default. The parameter "port" specifies the TCP port. LoadPlugin "olsrd_dot_draw.so.0.3" { PlParam "accept" "192.168.0.5" PlParam "port" "2004" } Then restart olsr and check if you get output on TCP Port 2004 telnet localhost 2004

After a while you should get some text output. Now you can save the output graph descriptions and run the tools dot or neato form the graphviz package to get images. Bruno Randolf has written a small perl script which continuously gets the topology information from olsrd and displays it using the graphviz and Image- Magick tools. First install the following packages on your workstation: graphviz, http://www.graphviz.org ImageMagick, http://www.imagemagick.org Download the script at: http://meshcube.org/nylon/utils/olsr-topology-view.pl Or from here: ftp://ftp.internat.freebsd.org/pub/mesh/visualization/olsr-topology-view.pl Now you can start the script with ./olsr-topology-view.pl and view the topology updates in nearrealtime. Here is the script if you are not able to download it:

#!/usr/bin/perl # a hack to display OLSR topology information # # copyleft 2004 Bruno Randolf <br1@subnet.at> # licensed under the GPL use IO::Socket; use Getopt::Long; $TOPPATH = "/tmp"; $NAME = "topology"; $FILENAME = "$TOPPATH/$NAME.dot"; $EXT = "png"; $SERVER = "localhost"; $PORT = "2004"; $FULLSCREEN = 0; $HELP = 0; $KEEP = 0; $BGCOLOR = "black"; $STYLE = 1; $SIZE = "8,8"; $ROOTWIN = 0; $ONCE = 0; $GRAPH = 1; $SHOW = 1; $FONTNAME = "Courier"; $FONTSIZE = 12; $LINEWIDTH = 0; $LINECOLOR = 0; $RESOLV = 0;

GetOptions ("server=s" => \$SERVER, "port=s" => \$PORT, "fullscreen!" => \$FULLSCREEN, "help!" => \$HELP, "keep!" => \$KEEP, "bgcolor=s" => \$BGCOLOR, "fontname=s" => \$FONTNAME, "fontsize=s" => \$FONTSIZE, "style=i" => \$STYLE, "size=s" => \$SIZE, "rootwin!" => \$ROOTWIN, "once!" => \$ONCE, "graph!" => \$GRAPH, "show!" => \$SHOW, "linewidth!" => \$LINEWIDTH, "linecolor!" => \$LINECOLOR, "resolv" => \$RESOLV, ); if ($HELP) { print << "EOF"; usage: $0 [ --server SERVER ] [--port PORT] [--fullscreen] [--keep] a hack to display OLSR topology information options: --server SERVER connect to OLSR node (default: localhost) --port PORT connect to port (default: 2004) --bgcolor background color (default: black) --fontname font name (default: Courier) --fontsize font size (default: 12) --style drawing style 1, 2 or 3 (default:1) --size X,Y image size in inches for graphviz (default: 8,8) --[no]fullscreen display fullscreen (default: off) --[no]rootwin display in root window (default: off) --[no]graph genereate graphics (default: on) --[no]show display the graphics (default: on) --[no]once run only 1 time, then exit (default: run forever) --[no]linewith change line width according to metric (default: off) --[no]linecolor change line color according to metric (default: off) --[no]resolv resolv hostnames (default: off) --[no]keep keep the .dot files with timestamp in /tmp (default: off) requires the "graphviz" and "imagemagick" packages installed and the "olsrd_dot_draw" plugin configured on the olsr node

EOF exit; } `touch $TOPPATH/$NAME.$EXT`; $remote = IO::Socket::INET->new( Proto => "tcp", PeerAddr => $SERVER, PeerPort => $PORT, ) or die "cannot connect to port $PORT at $SERVER!\nis the olsrd_dot_draw plugin loaded and configured to allow connections from this host?\n"; $f; $start = 1; $FULLOPT = "-backdrop -background black" if $FULLSCREEN; if ($STYLE == 1) { $DOT_CMD = "neato -Tpng -Gsize=${SIZE} -Gbgcolor=${BGCOLOR} Gsplines=true -Nstyle=filled -Nfontname=${FONTNAME} -Nfontsize=${FONTSIZE} Efontname=${FONTNAME} -Efontsize=${FONTSIZE} -Ncolor=white -Nfillcolor=white Ecolor=grey -Elen=4 -Earrowsize=2 -Efontcolor=white $FILENAME -o $TOPPATH/$NAME.new"; } elsif ($STYLE == 2) { $BGCOLOR = "grey"; $DOT_CMD = "dot -Tpng -Gsize=${SIZE} -Elen=2 -Ncolor=grey -Nstyle=filled Nfillcolor=white -Nfontname=${FONTNAME} -Nfontsize=${FONTSIZE} Efontname=${FONTNAME} -Efontsize=${FONTSIZE} -Nfontcolor=red -Nwidth=1 Gbgcolor=$BGCOLOR $FILENAME -o $TOPPATH/$NAME.new"; } elsif ($STYLE == 3) { $BGCOLOR = "\#ff6600"; $DOT_CMD = "neato -Tpng -Gsize=10,9 -Gbgcolor=${BGCOLOR} -Gsplines=true Nstyle=filled -Nfontname=${FONTNAME} -Nfontsize=${FONTSIZE} Efontname=${FONTNAME} -Efontsize=${FONTSIZE} -Nheight=1.3 -Nwidth=1.3 Gsplines=true -Ncolor=darkslategrey -Nfillcolor=darkslategrey -Ecolor=black -Elen=4 Earrowsize=3 $FILENAME -o $TOPPATH/$NAME.new"; } while ( <$remote> )

{ $line = $_; if ($RESOLV) { $line = resolv( $line ); } if ($LINEWIDTH || $LINECOLOR) { $line = draw_thicker_metric_lines( $line ); } $f = $f . $line; # end of one graph if ( $line =~ /}/i ) { #print "* "; open DOTFILE, ">$FILENAME"; print DOTFILE $f; close DOTFILE; $f = ""; if ($GRAPH) { `$DOT_CMD`; `mv $TOPPATH/$NAME.new $TOPPATH/$NAME.$EXT`; } if ($KEEP) { `cp $TOPPATH/$NAME.dot $TOPPATH/$NAME-\$(date +'%Y%m-%d-%H-%M-%S').dot`; } if ($SHOW) { if ($ROOTWIN) { system "display -window root -backdrop $TOPPATH/$NAME.$EXT &"; } elsif ($start) { system "display $FULLOPT -update 5 $TOPPATH/$NAME.$EXT &"; $start = 0; } } exit if $ONCE; } } print "connection closed\n"; sub resolv { my $l = shift;

if ( $l =~ /\"(.*)\" -> "([^[]*)"(.*)/) { my $from = $1; my $to = $2; my $rest = $3; $from =~ s/\"//g; $to =~ s/\"//g; my $iaddrf = inet_aton($from); my $fromn = gethostbyaddr($iaddrf, AF_INET); my $iaddrt = inet_aton($to); my $ton = gethostbyaddr($iaddrt, AF_INET); $fromn = $from if ! $fromn; $ton = $to if ! $ton; $l = "\"$fromn\" -> \"$ton\"$rest\n"; } return $l; } sub draw_thicker_metric_lines { # sla 04.04.2005 # a hack to draws thicker lines for better metrics (the better the thicker). # colorize the metric lines. # my $l = shift; if ($l =~ /.*label="[0-9].*/){ # recognizion pattern @n=split (/"/,$l); # split the string to get the metric value if ($LINECOLOR) { if ( $n[5]>2 ) { # colorize metrics greater than 2 gray $c="888888"; } else { # colorize metrics less than 2 black $c="000000"; } $setcol = "color=\"#$c\","; } if ($LINEWIDTH) { if ($n[5]>0 && $n[5]<10) { # thicker lines if 10 > metric > 0 $lt=6/$n[5]; $at=$lt/2; } else { # at least draw a thin line $lt=1; $at=$lt; } $setwidth = "style=\"setlinewidth($lt)\", arrowsize=$at"; }

$l =~ s/\]/, $setcol $setwidth]/g; # replace pattern } return $l; } __END__

Troubleshooting As long as the WiFi-cards can 'see' each other directly with their radios, doing a ping will work whether olsrd is running or not. This works because the large netmasks effectively make every node link-local, so routing issues are sidestepped at the first hop. This should be checked first if things do not seem to work as expected. Most headaches people face with WiFi in Ad-Hoc mode are caused by the fact that the ad-hoc mode in drivers and cards are implemented sloppily. If it is not possible to ping nodes directly when they are in range it is most likely a card/driver issue, or your network settings are wrong. If the machines can ping each other, but olsrd doesn't find routes, then the IP-addresses, netmask and broadcast address should be checked. Finally, are you running a firewall? Make sure it doesn't block UDP port 698.

Estimating capacity Wireless links can provide significantly greater throughput to users than traditional Internet connections, such as VSAT, dialup, or DSL. Throughput is also referred to as channel capacity, or simply bandwidth (although this term is unrelated to radio bandwidth). It is important to understand that a wireless devices listed speed (the data rate) refers to the rate at which the radios can exchange symbols, not the usable throughput you will observe. As mentioned earlier, a single 802.11g link may use 54 Mbps radios, but it will only provide up to 22 Mbps of actual throughput. The rest is overhead that the radios need in order to coordinate their signals using the 802.11g protocol. Note that throughput is a measurement of bits over time. 22 Mbps means that in any given second, up to 22 megabits can be sent from one end of the link to the other. If users attempt to push more than 22 megabits through the link, it will take longer than one second. Since the data cant be sent immediately, it is put in a queue, and transmitted as quickly as possible. This backlog of data increases the time needed for the most recently queued bits to the traverse the link. The time that it takes for data to traverse a link is called latency, and high latency is commonly referred to as lag. Your link will eventually send all of the queued traffic, but your users will likely complain as the lag increases. How much throughput will your users really need? It depends on how many users you have, and how they use the wireless link. Various Internet applications require different amounts of throughput.

Application Text messaging / IM

BW / User

Note

Email

Web

Streaming audio

Voice over IP

Streaming video

Peer-to-peer file sharing (BitTorrent, KaZaA, Gnutella, eDonkey, etc.)

<1 kbps As traffic is infrequent and asynchronous, IM will tolerate high latency. As with IM, email is asynchronous and intermittent, so it will 1-100 tolerate latency. Large attachments, viruses, and spam significantly add to bandwidth kbps usage. Note that web email services (such as Yahoo or Hotmail) should be considered as web browsing, not as email. Web browsers only use the network when data is requested. 50-100 Communication is asynchronous, so a fair amount of lag can kbps + be tolerated. As web browsers request more data (large images, long downloads, etc.) bandwidth usage will go up significantly. Each user of a streaming audio service will use a constant 96-160 amount of relatively large bandwidth for as long as it plays. It can tolerate some transient latency by using kbps large buffers on the client. But extended periods of lag will cause audio skips or outright session failures. As with streaming audio, VoIP commits a constant amount of bandwidth to each user for the duration of the call. But with 24-100 VoIP, the bandwidth is used roughly equally in kbps both directions. Latency on a VoIP connection is immediate and annoying to users. Lag greater than a few milliseconds is unacceptable for VoIP.. 64-200 As with streaming audio, some intermittent latency is avoided by using buffers on the client. Streaming video requires high kbps throughput and low latency to work properly. While peer to peer applications will tolerate any amount of latency, they tend to use up all available throughput by 0infinite transmitting data to as many clients as possible, as quickly as possible. Use of these applications will cause latency and Mbps throughput problems for all other network users unless you use careful bandwidth shaping..

To estimate the necessary throughput you will need for your network, multiply the expected number of users by the sort of application they will probably use. For example, 50 users who are chiefly browsing the web will likely consume 2.5 to 5 Mbps or more of throughput at peak times, and will tolerate some latency. On the other hand, 50 simultaneous VoIP users would require 5 Mbps or more of throughput in both directions with absolutely no latency. Since 802.11g wireless equipment is half duplex (that is, it only transmits or receives, never both at once) you should accordingly double the required throughput, for a total of 10 Mbps. Your wireless links must provide that capacity every second, or conversations will lag.

Since all of your users are unlikely to use the connection at precisely the same moment, it is common practice to oversubscribe available throughput by some factor (that is, allow more users than the maximum available band-width can support). Oversubscribing by a factor of 2 to 5 is quite common. In all likelihood, you will oversubscribe by some amount when building your network infrastructure. By carefully monitoring throughput throughout your network, you will be able to plan when to upgrade various parts of the network, and how much additional resources will be needed. Expect that no matter how much capacity you supply, your users will eventually find applications that will use it all. As well see at the end of this chapter, using bandwidth shaping techniques can help mitigate some latency problems. By using bandwidth shaping, web caching, and other techniques, you can significantly reduce latency and increase overall network throughput. To get a feeling for the lag felt on very slow connections, the ICTP has put together a bandwidth simulator. It will simultaneously download a web page at full speed and at a reduced rate that you choose. This demonstration gives you an immediate understanding of how low throughput and high latency reduce the usefulness of the Internet as a communications tool. It is available at http://wireless.ictp.trieste.it/simulator/

Link planning A basic communication system consists of two radios, each with its associated antenna, the two being separated by the path to be covered. In order to have a communication between the two, the radios require a certain minimum signal to be collected by the antennas and presented to their input socket. Determining if the link is feasible is a process called link budget calculation. Whether or not signals can be passed between the radios depends on the quality of the equipment being used and on the diminishment of the signal due to distance, called path loss.

Calculating the link budget The power available in an 802.11 system can be characterized by the following factors: Transmit Power. It is expressed in milliwatts or in dBm. Transmit Power ranges from 30mW to 200mW or more. TX power is often dependent on the transmission rate. The TX power of a given device should be specified in the literature provided by the manufacturer, but can sometimes be difficult to find. Online databases such as the one provided by SeattleWireless (http://www.seattlewireless.net/HardwareComparison) may help. Antenna Gain. Antennas are passive devices that create the effect of amplification by virtue of their physical shape. Antennas have the same characteristics when receiving and transmitting. So a 12 dBi antenna is simply a 12 dBi antenna, without specifying if it is in transmission or reception mode. Parabolic antennas have a gain of 19-24 dBi, omnidirectional antennas have 512 dBi, sectorial antennas have roughly a 12-15 dBi gain.

Minimum Received Signal Level, or simply, the sensitivity of the receiver. The minimum RSL is always expressed as a negative dBm (- dBm) and is the lowest power of signal the radio can distinguish. The minimum RSL is dependent upon rate, and as a general rule the lowest rate (1 Mbps) has the greatest sensitivity. The minimum will be typically in the range of -75 to -95 dBm. Like TX power, the RSL specifications should be provided by the manufacturer of the equipment. Cable Losses. Some of the signal's energy is lost in the cables, the connectors and other devices, going from the radios to the antennas. The loss depends on the type of cable used and on its length. Signal loss for short coaxial cables including connectors is quite low, in the range of 2-3 dB. It is better to have cables as short as possible. When calculating the path loss, several effects must be considered. One has to take into account the free space loss, attenuation and scattering. Signal power is diminished by geometric spreading of the wavefront, commonly known as free space loss. Ignoring everything else, the further away the two radios, the smaller the received signal is due to free space loss. This is independent from the environment, depending only on the distance. This loss happens because the radiated signal energy expands as a function of the distance from the transmitter. Using decibels to express the loss and using 2.45 GHz as the signal frequency, the equation for the free space loss is Lfsl = 40 + 20*log(r) Where Lfsl is expressed in dB and r is the distance between the transmitter and receiver, in meters. The second contribution to the path loss is given by attenuation. This takes place as some of the signal power is absorbed when the wave passes through solid objects such as trees, walls, windows and floors of buildings. Attenuation can vary greatly depending upon the structure of the object the signal is passing through, and it is very difficult to quantify. The most convenient way to express its contribution to the total loss is by adding an allowed loss to the free space. For example, experience shows that trees add 10 to 20 dB of loss per tree in the direct path, while walls contribute 10 to 15 dB depending upon the construction. Along the link path, the RF energy leaves the transmitting antenna and energy spreads out. Some of the RF energy reaches the receiving antenna directly, while some bounces off the ground. Part of the RF energy which bounces off the ground reaches the receiving antenna. Since the reflected signal has a longer way to travel, it arrives at the receiving antenna later than the direct signal. This effect is called multipath, or signal dispersion. In some cases reflected signals add together and cause no problem. When they add together out of phase, the received signal is almost worthless. In some cases, the signal at the receiving antenna can be zeroed by the reflected signals. This is known as extreme fading, or nulling. There is a simple technique that is used to deal with multipath, called antenna diversity. It consists of adding a second antenna to the radio. Multipath is in fact a very location-specific phenomenon. If two signals add out of phase at one location, they will not add destructively at a second, nearby location. If there are two antennas, at least one of them should be able to receive a usable signal, even if the other is receiving a distorted one. In commercial devices, antenna switching diversity is used: there are multiple

antennas on multiple inputs, with a single receiver. The signal is thus received through only one antenna at a time. When transmitting, the radio uses the antenna last used for reception. The distortion given by multipath degrades the ability of the receiver to recover the signal in a manner much like signal loss. A simple way of applying the effects of scattering in the calculation of the path loss is to change the exponent of the distance factor of the free space loss formula. The exponent tends to increase with the range in an environment with a lot of scattering. An exponent of 3 can be used in an outdoor environment with trees, while one of 4 can be used for an indoor environment. When free space loss, attenuation, and scattering are combined, the path loss is: L(dB) = 40 + 10*n*log(r) + L(allowed) For a rough estimate of the link feasibility, one can evaluate just the free space loss. The environment can bring further signal loss, and should be considered for an exact evaluation of the link. The environment is in fact a very important factor, and should never be neglected. To evaluate if a link is feasible, one must know the characteristics of the equipment being used and evaluate the path loss. Note that when performing this calculation, you should only add the TX power of one side of the link. If you are using different radios on either side of the link, you should calculate the path loss twice, once for each direction (using the appropriate TX power for each calculation). Adding up all the gains and subtracting all the losses gives: TX Power Radio 1 + Antenna Gain Radio 1 - Cable Losses Radio 1 + Antenna Gain Radio 2 - Cable Losses Radio 2 -------------------------------------------= Total Gain Subtracting the Path Loss from the Total Gain: Total Gain - Path Loss -----------------------------------------------------------= Signal Level at one side of the link If the resulting signal level is greater than the minimum received signal level, then the link is feasible! The received signal is powerful enough for the radios to use it. Remember that the minimum RSL is always expressed as a negative dBm, so -56 dBm is greater than -70 dBm. On a given path, the variation in path loss over a period of time can be large, so a certain margin (difference between the signal level and the minimum received signal level) should be considered. This margin is the amount of signal above the sensitivity of radio that should be received in order to ensure a stable, high quality radio link during bad weather and other atmospheric disturbances. A margin of 10 to 15 dB is fine. To give some space for attenuation and multipath in the received radio signal, a margin of 20dB should be safe enough.

Once you have calculated the link budget in one direction, repeat the calculation for the other direction. Substitute the transmit power for that of the second radio, and compare the result against the minimum received signal level of the first radio.

Example link budget calculation As an example, we want to estimate the feasibility of a 5 km link, with one access point and one client radio. The access point is connected to an omnidirectional antenna with 10 dBi gain, while the client is connected to a sectorial antenna with 14 dBi gain. The transmitting power of the AP is 100mW (or 20 dBm) and its sensitivity is -89 dBm. The transmitting power of the client is 30mW (or 15 dBm) and its sensitivity is -82 dBm. The cables are short, with a loss of 2dB at each side.Adding up all the gains and subtracting all the losses for the AP to client link gives: 20 dBm (TX Power Radio 1) + 10 dBi (Antenna Gain Radio 1) - 2 dB (Cable Losses Radio 1) + 14 dBi (Antenna Gain Radio 2) - 2 dB (Cable Losses Radio 2) -----------------------------------------------------40 dB = Total Gain The path loss for a 5 km link, considering only the free space loss is: Path Loss = 40 + 20log(5000) = 113 dB Subtracting the path loss from the total gain 40 dB - 113 dB = -73 dB Since -73 dB is greater than the minimum receive sensitivity of the client radio (-82 dBm), the signal level is just enough for the client radio to be able to hear the access point. There is only 9 dB of margin (82 dB - 73 dB) which will likely work fine in fair weather, but may not be enough to protect against extreme weather conditions. Next we calculate the link from the client back to the access point: 15 dBm (TX Power Radio 2) + 14 dBi (Antenna Gain Radio 2) - 2 dB (Cable Losses Radio 2) + 10 dBi (Antenna Gain Radio 1) - 2 dB (Cable Losses Radio 1) -------------------------------------------------35 dB = Total Gain

Obviously, the path loss is the same on the return trip. So our received signal level on the access point side is: 35 dB - 113 dB = -78 dB Since the receive sensitivity of the AP is -89dBm, this leaves us 11dB of fade margin (89dB 78dB). Overall, this link will probably work but could use a bit more gain. By using a 24dBi dish on the client side rather than a 14dBi sectorial antenna, you will get an additional 10dBi of gain on both directions of the link (remember, antenna gain is reciprocal). A more expensive option would be to use higher power radios on both ends of the link, but note that adding an amplifier or higher powered card to one end generally does not help the overall quality of the link. Online tools can be used to calculate the link budget. For example, the Green Bay Professional Packet Radios Wireless Network Link Analysis (http://my.athenet.net/~multiplx/cgibin/wireless.main.cgi ) is an excellent tool. The Super Edition generates a PDF file containing the Fresnel zone and radio path graphs. The calculation scripts can even be downloaded from the website and installed locally. The Terabeam website also has excellent calculators available online: http://www.terabeam.com/support/calculations/index.php , http://www.terabeam.com/support/calculations/index.php More online calculator: http://www.pizon.org/rf-tools/watts-to-dbm-converter.php http://www.qsl.net/n9zia/wireless/page09.html http://www.wirelessconnections.net/calcs/calculations.asp http://www.wirelessconnections.net/calcs/BudgetCalc.asp http://www.ratrivertech.ca/archives/tools/downtilt_coverage_calculator.htm http://www.netkrom.com/free_space_calculator.php?re2=cal&item=resources http://kb9mwr.dyndns.org/n9zia/path.main.cgi http://kb9mwr.dyndns.org/n9zia/wireless.main.cgi http://www.wlanantennas.com/downtilt_cover.php http://www.radiolabs.com/stations/wifi_calc.html http://www.afar.net/rf-link-budget-calculator/ http://www.proxim.com/products/knowledge-center/calculations

Tables for calculating link budget To calculate the link budget, simply approximate your link distance, then fill in the following tables: Free Space Path Loss at 2.4 GHz Distance (m) Loss (dB) 100 80 500 94 1000 100 3000 110 5000 113 10 000 120 Antenna Gain: Radio Antenna 1 + Radio Antenna 2 = Total Strengthening Antenna Losses: Radio 1 Cable Loss (dB)+Radio 2 Cable Loss (dB)+Free Space Path Loss (dB)= Total Loss (dB) Link Budget for Radio 1 Radio 2: Radio 1 TX Power+ Antenna Gain- Total Loss= Signal> Radio 2 Sensitivity Link Budget for Radio 2 Radio 1: Radio 2 TX Power+ Antenna Gain- Total Loss= Signal> Radio 1 Sensitivity If the received signal is greater than the minimum received signal strength in both directions of the link, as well as any noise received along the path, then the link is possible.

Link planning software While calculating a link budget by hand is straightforward, there are a number of tools available that will help automate the process. In addition to calculating free space loss, these tools will take many other relevant factors into account as well (such as tree absorption, terrain effects, climate, and even estimating path loss in urban areas). In this section, we will discuss two free tools that are useful for planning wireless links: Green Bay Professional Packet Radios online interactive network design utilities, and RadioMobile. Interactive design CGIs The Green Bay Professional Packet Radio group (GBPRR) has made a variety of very useful link planning tools available for free online. You can browse these tools online at http://www.qsl.net/n9zia/wireless/page09.html . Since the tools are available online, they will work with any device that has a web browser and Internet access. We will look at the first tool, Wireless Network Link Analysis, in detail. You can find it online at http://my.athenet.net/~multiplx/cgi-bin/wireless.main.cgi. To begin, enter the channel to be used on the link. This can be specified in MHz or GHz. If you dont know the frequency, consult the table in AppendixB. Note that the table lists the channels center frequency, while the tool asks for the highest transmitted frequency. The difference in the ultimate result is minimal, so feel free to use the center frequency instead. To find the highest transmitted frequency for a channel, just add 11MHz to the center frequency. Next, enter the details for the transmitter side of the link, including the transmission line type, antenna gain, and other details. Try to fill in as much data as you know or can estimate. You can also enter the antenna height and elevation for this site. This data will be used for calculating the antenna tilt angle. For calculating Fresnel zone clearance, you will need to use GBPRRs Fresnel Zone Calculator. The next section is very similar, but includes information about the other end of the link. Enter all available data in the appropriate fields. Finally, the last section describes the climate, terrain, and distance of the link. Enter as much data as you know or can estimate. Link distance can be calculated by specifying the latitude and longitude of both sites, or entered by hand. Now, click the Submit button for a detailed report about the proposed link. This includes all of the data entered, as well as the projected path loss, error rates, and uptime. These numbers are all completely theoretical, but will give you a rough idea of the feasibility of the link. By adjusting values on the form, you can play what-if? to see how changing various parameters will affect the connection. In addition to the basic link analysis tool, GBPRR provides a super edition that will produce a PDF report, as well as a number of other very useful tools (including the Fresnel Zone Calculator, Distance & Bearing Calculator, and Decibel Conversion Calculator to name just a few). Source code to most of the tools is provided as well.

RadioMobile Radio Mobile is a tool for the design and simulation of wireless systems. It predicts the performance of a radio link by using information about the equipment and a digital map of the area. It is public domain software that runs on Windows, or using Linux and the Wine emulator. Radio Mobile uses a digital terrain elevation model for the calculation of coverage, indicating received signal strength at various points along the path. It automatically builds a profile between two points in the digital map showing the coverage area and first Fresnel zone. During the simulation, it checks for line of sight and calculates the Path Loss, including losses due to obstacles. It is possible to create networks of different topologies, including net master/ slave, point-to-point, and point-to-multipoint. The software calculates the coverage area from the base station in a point-to-multipoint system. It works for systems having frequencies from 100 kHz to 200 GHz. Digital elevation maps (DEM) are available for free from several sources, and are available for most of the world. DEMs do not show coastlines or other readily identifiable landmarks, but they can easily be combined with other kinds of data (such as aerial photos or topographical charts) in several layers to obtain a more useful and readily recognizable representation. You can digitize your own maps and combine them with DEMs. The digital elevation maps can be merged with scanned maps, satellite photos and Internet map services (such as Google Maps) to produce accurate prediction plots.

Link feasibility, including Fresnel zone and line of sight estimate, using RadioMobile. The main Radio Mobile webpage, with examples and tutorials, is available at: http://www.cplus.org/rmw/english1.html RadioMobile under Linux Radio Mobile will also work using Wine under Ubuntu Linux. While the application runs, some button labels may run beyond the frame of the button and can be hard to read. We were able to make Radio Mobile work with Linux using the following environment: IBM Thinkpad x31 Ubuntu Breezy (v5.10), http://www.ubuntu.com/ Wine version 20050725, from the Ubuntu Universe repository There are detailed instructions for installing RadioMobile on Windows at http://www.cplus.org/rmw/english1.html . You should follow all of the steps except for step 1

(since it is difficult to extract a DLL from the VBRUN60SP6.EXE file under Linux). You will either need to copy the MSVBVM60.DLL file from a Windows machine that already has the Visual Basic 6 run-time environment installed, or simply Google for MSVBVM60.DLL, and download the file. Now continue with step 2 at from the above URL, making sure to unzip the downloaded files in the same directory into which you have placed the downloaded DLL file. Note that you don't have to worry about the stuff after step 4; these are extra steps only needed for Windows users. Finally, you can start Wine from a terminal with the command: # wine RMWDLX.exe You should see RadioMobile running happily in your XWindows session.

Avoiding noise The unlicensed ISM and U-NII bands represent a very tiny piece of the known electromagnetic spectrum. Since this region can be utilized without paying license fees, many consumer devices use it for a wide range of applications. Cordless phones, analog video senders, Bluetooth, baby monitors, and even microwave ovens compete with wireless data networks for use of the very limited 2.4GHz band. These signals, as well as other local wireless networks, can cause significant problems for long range wireless links. Here are some steps you can use to reduce reception of unwanted signals. Increase antenna gain on both sides of a point-to-point link. Antennas not only add gain to a link, but their increased directionality tends to reject noise from areas around the link. Two high gain dishes that are pointed at each other will reject noise from directions that are outside the path of the link. Using omnidirectional antennas will receive noise from all directions.

A single omnidirectional antenna vs. multiple sectorials

Use sectorials instead of using an omnidirectional. By making use of several sectorial antennas, you can reduce the overall noise received at a distribution point. By staggering the channels used on each sectorial, you can also increase the available bandwidth to your clients. Dont use an amplifier. As we will see in Chapter 4, amplifiers can make interference issues worse by indiscriminately amplifying all received signals, including sources of interference. Amplifiers also cause interference problems for other nearby users of the band. Use the best available channel. Remember that 802.11b/g channels are 22 MHz wide, but are only separated by 5MHz. Perform a site survey, and select a channel that is as far as possible from existing sources of interference. Remember that the wireless landscape can change at any time as people add new devices (cordless phones, other networks, etc.) If your link suddenly has trouble sending packets, you may need to perform another site survey and pick a different channel. Use smaller hops and repeaters, rather than a single long distance shot. Keep your pointto-point links as short as possible. While it may be possible to create a 12 km link that cuts across the middle of a city, you will likely have all kinds of interference problems. If you can break that link into two or three shorter hops, the link will likely be more stable. Obviously this isnt possible on long distance rural links where power and mounting structures are unavailable, but noise problems are also unlikely in those settings. If possible, use 5.8GHz, 900MHz, or another unlicensed band. While this is only a short term solution, there is currently far more consumer equipment installed in the field that uses 2.4 GHz. Using 802.11a or a 2.4GHz to 5.8GHz step-up device will let you avoid this congestion altogether. If you can find it, some old 802.11 equipment uses unlicensed spectrum at 900MHz (unfortunately at much lower bit rates). Other technologies, such as Ronja (http://ronja.twibright.com ) use optical technology for short distance, noise-free links. If all else fails, use licensed spectrum. There are places where all available unlicensed spectrum is effectively used. In these cases, it may make sense to spend the additional money for proprietary equipment that uses a less congested band. For long distance point-to-point links that require very high throughput and maximum uptime, this is certainly an option. Of course, these features come at a much higher price tag compared to unlicensed equipment. To identify sources of noise, you need tools that will show you what is happening in the air at 2.4GHz. you will see some examples later.

Repeaters The most critical component to building long distance network links is line of sight (often abbreviated as LOS). Terrestrial microwave systems simply cannot tolerate large hills, trees, or other obstacles in the path of a long distance link. You must have a clear idea of the lay of the land between two points before you can determine if a link is even possible. But even if there is a mountain between two points, remember that obstacles can sometimes be turned into assets. Mountains may block your signal, but assuming power can be provided they

also make very good repeater sites. Repeaters are nodes that are configured to rebroadcast traffic that is not destined for the node itself. In a mesh network, every node is a repeater. In a traditional infrastructure network, nodes must be configured to pass along traffic to other nodes. A repeater can use one or more wireless devices. When using a single radio (called a one-arm repeater), overall efficiency is slightly less than half of the available bandwidth, since the radio can either send or receive data, but never both at once. These devices are cheaper, simpler, and have lower power requirements. A repeater with two (or more) radio cards can operate all radios at full capacity, as long as they are each configured to use nonoverlapping channels. Of course, repeaters can also supply an Ethernet connection to provide local connectivity. Repeaters can be purchased as a complete hardware solution, or easily assembled by connecting two or more wireless nodes together with Ethernet cable. When planning to use a repeater built with 802.11 technologies, remember that nodes must be configured for master, managed, or adhoc mode. Typically, both radios in a repeater are configured for master mode, to allow multiple clients to connect to either side of the repeater. But depending on your network layout, one or more devices may need to use ad-hoc or even client mode.

The repeater forwards packets over the air between nodes that have no direct line of sight.

Typically, repeaters are used to overcome obstacles in the path of a long distance link. For example, there may be buildings in your path, but those buildings contain people. Arrangements can often be worked out with building owners to provide bandwidth in exchange for roof rights and electricity. If the building owner isnt interested, tenants on high floors may be able to be persuaded to install equipment in a window. If you cant go over or through an obstacle, you can often go around it. Rather than using a direct link, try a multi-hop approach to avoid the obstacle.

No power was available at the top of the hill, but it was circumvented byusing multiple repeater sites around the base. Finally, you may need to consider going backwards in order to go forwards. If there is a high site available in a different direction, and that site can see beyond the obstacle, a stable link can be made via an indirect route.

Site D could not make a clean link to site A or B, since site C is in the way and is not hosting a node. By installing a high repeater, nodes A, B, and D can communicate with each other. Note that traffic from node D actually travels further away from the rest of the network before the repeater forwards it along. Repeaters in networks remind me of the six degrees of separation principle. This idea says that no matter who you are looking for, you need only contact five intermediaries before finding the person. Repeaters in high places can see a great deal of intermediaries, and as long as your node is in range of the repeater, you can communicate with any node the repeater can reach.

Traffic optimization Bandwidth is measured as the amount of bits transmitted over a time interval. This means that over time, bandwidth available on any link approaches infinity. Unfortunately, for any given period of time, the bandwidth provided by any given network connection is not infinite. You can always download (or upload) as much traffic as you like; you need only wait long enough. Of

course, human users are not as patient as computers, and are not willing to wait an infinite amount of time for their information to traverse the network. For this reason, bandwidth must be managed and prioritized much like any other limited resource. You will significantly improve response time and maximize available throughput by eliminating unwanted and redundant traffic from your network. This section describes a few common techniques for making sure that your network carries only the traffic that must traverse it. For a more thorough discussion of the complex subject of bandwidth optimization, see the free book How to Accelerate Your Internet (http://bwmo.net): http://bwmo.net/pdf/bwmo-ebook.pdf

Web caching A web proxy server is a server on the local network that keeps copies of recently retrieved or often used web pages, or parts of pages. When the next person retrieves these pages, they are served from the local proxy server instead of from the Internet. This results in significantly faster web access in most cases, while reducing overall Internet bandwidth usage. When a proxy server is implemented, the administrator should also be aware that some pages are not cacheable-- for example, pages that are the output of serverside scripts, or other dynamically generated content. The apparent loading of web pages is also affected. With a slow Internet link, a typical page begins to load slowly, first showing some text and then displaying the graphics one by one. In a network with a proxy server, there could be a delay when nothing seems to happen, and then the page will load almost at once. This happens because the information is sent to the computer so quickly that it spends a perceptible amount of time rendering the page. The overall time it takes to load the whole page might take only ten seconds (whereas without a proxy server, it may take 30 seconds to load the page gradually). But unless this is explained to some impatient users, they may say the proxy server has made things slower. It is usually the task of the network administrator to deal with user perception issues like these.

Proxy server products There are a number of web proxy servers available. These are the most commonly used software packages: Squid. Open source Squid is the de facto standard at universities. It is free, reliable, easy to use and can be enhanced (for example, adding content filtering and advertisement blocking). Squid produces logs that can be analyzed using software such as Awstats, or Webalizer, both of which are open source and produce good graphical reports. In most cases, it is easier to install as part of the distribution than to download it from http://www.squid-cache.org/ (most Linux distributions such as Debian, as well as other versions of Unix such as NetBSD and FreeBSD come with Squid). A good Squid configuration guide can be found on the Squid Users Guide Wiki at http://www.deckle.co.za/squid-users-guide/. Microsoft Proxy server 2.0. Not available for new installations because it has been superseded by Microsoft ISA server and is no longer supported. It is nonetheless used by some institutions, although it should perhaps not be considered for new installations.

Microsoft ISA server. ISA server is a very good proxy server program, that is arguably too expensive for what it does. However, with academic discounts it may be affordable to some institutions. It produces its own graphical reports, but its log files can also be analyzed with popular analyzer software such as Sawmill (http://www.sawmill.net/). Administrators at a site with MS ISA Server should spend sufficient time getting the configuration right; otherwise MS ISA Server can itself be a considerable bandwidth user. For example, a default installation can easily consume more bandwidth than the site has used before, because popular pages with short expiry dates (such as news sites) are continually being refreshed. Therefore it is important to get the pre-fetching settings right, and to configure pre-fetching to take place mainly overnight. ISA Server can also be tied to content filtering products such as WebSense. For more information, see: http://www.microsoft.com/isaserver / and http://www.isaserver.org . Preventing users from bypassing the proxy server While circumventing Internet censorship and restrictive information access policy may be a laudable political effort, proxies and firewalls are necessary tools in areas with extremely limited bandwidth. Without them, the stability and usability of the network are threatened by legitimate users themselves. Techniques for bypassing a proxy server can be found at http://www.antiproxy.com .This site is useful for administrators to see how their network measures up against these techniques. To enforce use of the caching proxy, you might consider simply setting up a network access policy and trusting your users. In the layout below, the administrator has to trust that his users will not bypass the proxy server. In this case the administrator typically uses one of the following techniques: Not giving out the default gateway address through DCHP. This may work for a while, but some network-savvy users who want to bypass the proxy might find or guess the default gateway address. Once that happens, word tends to spread about how to bypass the proxy. Using domain or group policies. This is very useful for configuring the correct proxy server settings for Internet Explorer on all computers in the domain, but is not very useful for preventing the proxy from being bypassed, because it depends on a user logging on to the NT domain. A user with a Windows 95/98/ME computer can cancel his log-on and then bypass the proxy, and someone who knows a local user password on his Windows NT/2000/XP computer can log on locally and do the same. Begging and fighting with users. This approach, while common, is never an optimal situation for a network administrator.

This network relies on trusted users to properly configure their PCs to use the proxy server. The only way to ensure that proxies cannot be bypassed is by using the correct network layout, by using one of the three techniques described below. Firewall A more reliable way to ensure that PCs dont bypass the proxy can be implemented using the firewall. The firewall can be configured to allow only the proxy server to make HTTP requests to the Internet. All other PCs are blocked, as shown in below. Relying on a firewall may or may not be sufficient, depending on how the firewall is configured. If it only blocks access from the campus LAN to port 80 on web servers, there will be ways for clever users to find ways around it. Additionally, they will be able to use other bandwidth hungry protocols such as BitTorrent or Kazaa.

The firewall prevents PCs from accessing the Internet directly, but allows access via the proxy server.

Two network cards Perhaps the most reliable method is to install two network cards in the proxy server and connect the campus network to the Internet as shown below. In this way, the network layout makes it physically impossible to reach the Internet without going through the proxy server.

The only route to the Internet is through the proxy. The proxy server in this diagram should not have IP forwarding enabled, unless the administrators knows exactly what they want to let through. One big advantage to this design is that a technique known as transparent proxying can be used. Using a transparent proxy means that users web requests are automatically forwarded to the proxy server, without any need to manually configure web browsers to use it. This effectively forces all web traffic to be cached, eliminates many chances for user error, and will even work with devices that do not support use of a manual proxy. For more details about configuring a transparent proxy with Squid, see: http://www.squid-cache.org/Doc/FAQ/FAQ-17.html http://tldp.org/HOWTO/TransparentProxy.html

Policy-based routing One way to prevent bypassing of the proxy using Cisco equipment is with policy routing. The Cisco router transparently directs web requests to the proxy server. This technique is used at Makerere University. The advantage of this method is that, if the proxy server is down, the policy routes can be temporarily removed, allowing clients to connect directly to the Internet.

Mirroring a website With permission of the owner or web master of a site, the whole site can be mirrored to a local server overnight, if it is not too large. This is something that might be considered for important websites that are of particular interest to the organization or that are very popular with web users. This may have some use, but it has some potential pitfalls. For example, if the site that is mirrored contains CGI scripts or other dynamic content that require interactive input from the

user, this would cause problems. An example is a website that requires people to register online for a conference. If someone registers online on a mirrored server (and the mirrored script works), the organizers of the site will not have the information that the person registered. Because mirroring a site may infringe copyright, this technique should only be used with permission of the site concerned. If the site runs rsync, the site could be mirrored using rsync. This is likely the fastest and most efficient way to keep site contents synchronized. If the remote web server is not running rsync, the recommended software to use is a program called wget. It is part of most versions of Unix/Linux. A Windows version can be found at http://xoomer.virgilio.it/hherold , or in the free Cygwin Unix tools package (http://www.cygwin.com ). A script can be set up to run every night on a local web server and do the following: Change directory to the web server document root: for example, /var/ www/ on Unix, or C:\Inetpub\wwwroot on Windows. Mirror the website using the command: wget --cache=off -m http://www.python.org The mirrored website will be in a directory www.python.org. The web server should now be configured to serve the contents of that directory as a name-based virtual host. Set up the local DNS server to fake an entry for this site. For this to work, client PCs should be configured to use the local DNS server(s) as the primary DNS. (This is advisable in any case, because a local caching DNS server speeds up web response times).

Pre-populate the cache using wget Instead of setting up a mirrored website as described in the previous section, a better approach is to populate the proxy cache using an automated process. This method has been described by J. J. Eksteen and J. P. L. Cloete of the CSIR in Pretoria, South Africa, in a paper entitled Enhancing International World Wide Web Access in Mozambique Through the Use of Mirroring and Caching Proxies. In this paper (available at http://www.isoc.org/inet97/ans97/cloet.htm) they describe how the process works: "An automatic process retrieves the site's home page and a specified number of extra pages (by recursively following HTML links on the retrieved pages) through the use of a proxy. Instead of writing the retrieved pages onto the local disk, the mirror process discards the retrieved pages. This is done in order to conserve system resources as well as to avoid possible copyright conflicts. By using the proxy as intermediary, the retrieved pages are guaranteed to be in the cache of the proxy as if a client accessed that page. When a client accesses the retrieved page, it is served from the cache and not over the congested international link. This process can be run in off-peak times in order to maximize bandwidth utilization and not to compete with other access activities." The following command (scheduled to run at night once every day or week) is all that is needed (repeated for every site that needs pre-populating).

wget --proxy-on --cache=off --delete after -m http://www.python.org These options enable the following: -m: Mirrors the entire site. wget starts at www.python.org and follows all hyperlinks, so it downloads all subpages. --proxy-on: Ensures that wget makes use of the proxy server. This might not be needed in setups where a transparent proxy is employed. --cache=off: Ensures that fresh content is retrieved from the Internet, and not from the local proxy server. --delete after: Deletes the mirrored copy. The mirrored content remains in the proxy cache if there is sufficient disk space, and the proxy server caching parameters are set up correctly. In addition, wget has many other options; for example, to supply a password for websites that require them. When using this tool, Squid should be configured with sufficient disk space to contain all the pre-populated sites and more (for normal Squid usage involving pages other than the pre-populated ones). Fortunately, disk space is becoming ever cheaper and disk sizes are far larger than ever before. However, this technique can only be used with a few selected sites. These sites should not be too big for the process to finish before the working day starts, and an eye should be kept on disk space. Cache hierarchies When an organization has more than one proxy server, the proxies can share cached information among them. For example, if a web page exists in server A's cache, but not in the cache of server B, a user connected via server B might get the cached object from server A via server B. InterCache Protocol (ICP) and Cache Array Routing Protocol (CARP) can share cache information. CARP is considered the better protocol. Squid supports both protocols, and MS ISA Server supports CARP. For more information, See http://squid-docs.sourceforge.net/latest/html/c2075.html. This sharing of cached information reduces bandwidth usage in organizations where more than one proxy is used.

Proxy specifications On a university campus network, there should be more than one proxy server, both for performance and also for redundancy reasons. With today's cheaper and larger disks, powerful proxy servers can be built, with 50 GB or more disk space allocated to the cache. Disk performance is important; therefore the fastest SCSI disks would perform best (although an IDE based cache is better than none at all). RAID or mirroring is not recommended. It is also recommended that a separate disk be dedicated to the cache. For example, one disk could be for the cache, and a second for the operating system and cache logging. Squid is designed to use as much RAM as it can get, because when data is retrieved from RAM it is much faster than when it comes from the hard disk. For a campus network, RAM memory should be 1GB or more:

Apart from the memory required for the operating system and other applications, Squid requires 10 MB of RAM for every 1 GB of disk cache. Therefore, if there is 50 GB of disk space allocated to caching, Squid will require 500 MB extra memory. The machine would also require 128 MB for Linux and 128 MB for Xwindows. Another 256 MB should be added for other applications and in order that everything can run easily. Nothing increases a machine's performance as much as installing a large amount of memory, because this reduces the need to use the hard disk. Memory is thousands of times faster than a hard disk. Modern operating systems keep frequently accessed data in memory if there is enough RAM available. But they use the page file as an extra memory area when they don't have enough RAM.

DNS caching and optimization Caching-only DNS servers are not authoritative for any domains, but rather just cache results from queries asked of them by clients. Just like a proxy server that caches popular web pages for a certain time, DNS addresses are cached until their time to live (TTL) expires. This will reduce the amount of DNS traffic on your Internet connection, as the DNS cache may be able to satisfy many of the queries locally. Of course, client computers must be configured to use the cachingonly name server as their DNS server. When all clients use this server as their primary DNS server, it will quickly populate a cache of IP addresses to names, so that previously requested names can quickly be resolved. DNS servers that are authoritative for a domain also act as cache name-address mappings of hosts resolved by them.

Bind (named) Bind is the de facto standard program used for name service on the Internet. When Bind is installed and running, it will act as a caching server (no further configuration is necessary). Bind can be installed from a package such as a Debian package or an RPM. Installing from a package is usually the easiest method. In Debian, type apt-get install bind9 In addition to running a cache, Bind can also host authoritative zones, act as a slave to authoritative zones, implement split horizon, and just about everything else that is possible with DNS.

Dnsmasq One alternative caching DNS server is dnsmasq. It is available for BSD and most Linux distributions, or from http://www.thekelleys.org.uk/dnsmasq/. The big advantage of dnsmasq is flexibility: it easily acts as both a caching DNS proxy and an authoritative source for hosts and domains, without complicated zone file configuration. Updates can be made to zone data without even restarting the service. It can also serve as a DHCP server, and will integrate DNS service with DHCP host requests. It is very lightweight, stable, and extremely flexible. Bind is likely a better choice for very large networks (more than a couple of hundred nodes), but the simplicity and flexibility of dnsmasq makes it attractive for small to medium sized networks.

Windows NT To install the DNS service on Windows NT4: select Control Panel Network Services Add Microsoft DNS server. Insert the Windows NT4 CD when prompted. Configuring a caching-only server in NT is described in Knowledge Base article 167234. From the article: "Simply install DNS and run the Domain Name System Manager. Click on DNS in the menu, select New Server, and type in the IP address of your computer where you have installed DNS. You now have a caching only DNS server."

Windows 2000 Install DNS service: Start Settings Control Panel Add/Remove Software. In Add/Remove Windows Components, select Components Networking Services Details Domain Name System (DNS). Then start the DNS MMC (Start Programs Administrative Tools DNS) From the Action menu select "Connect To Computer..." In the Select Target Computer window, enable "The following computer:" and enter the name of a DNS server you want to cache. If there is a . [dot] in the DNS manager (this appears by default), this means that the DNS server thinks it is the root DNS server of the Internet. It is certainly not. Delete the . [dot] for anything to work.

Split DNS and a mirrored server The aim of split DNS (also known as split horizon) is to present a different view of your domain to the inside and outside worlds. There is more than one way to do split DNS; but for security reasons, it's recommended that you have two separate internal and external content DNS servers (each with different databases). Split DNS can enable clients from a campus network to resolve IP addresses for the campus domain to local RFC1918 IP addresses, while the rest of the Internet resolves the same names to different IP addresses. This is achieved by having two zones on two different DNS servers for the same domain. One of the zones is used by internal network clients and the other by users on the Internet. For example, in the network below the user on the Makerere campus gets http://www.makerere.ac.ug resolved to 172.16.16.21, whereas a user

elsewhere on the Internet gets it resolved to 195.171.16.13. The DNS server on the campus in the above diagram has a zone file for makerere.ac.ug and is configured as if it is authoritative for that domain. In addition, it serves as the DNS caching server for the Makerere campus, and all computers on the campus are configured to use it as their DNS server. The DNS records for the campus DNS server would look like this: makerere.ac.ug www ftp mail mailserver webserver ftpserver

CNAME webserver.makerere.ac.ug CNAME ftpserver.makerere.ac.ug CNAME exchange.makerere.ac.ug A 172.16.16.21 A 172.16.16.21 A 172.16.16.21

But there is another DNS server on the Internet that is actually authoritative for the akerere.ac.ug domain. The DNS records for this external zone would look like this: makerere.ac.ug www A 195.171.16.13 ftp A 195.171.16.13 mail A 16.132.33.21 MX mail.makerere.ac.ug Split DNS is not dependent on using RFC 1918 addresses. An African ISP might, for example, host websites on behalf of a university but also mirror those same websites in Europe. Whenever clients of that ISP access the website, it gets the IP address at the African ISP, and so the traffic stays in the same country. When visitors from other countries access that website, they get the IP address of the mirrored web server in Europe. In this way, international visitors do not congest the ISP's VSAT connection when visiting the university's website. This is becoming an attractive solution, as web hosting close to the Internet backbone has become very cheap.

Internet link optimization As mentioned earlier, network throughput of up to 22Mbps can be achieved by using standard, unlicensed 802.11g wireless gear. This amount of bandwidth will likely be at least an order of magnitude higher than that provided by your Internet link, and should be able to comfortably support many simultaneous Internet users. But if your primary Internet connection is through a VSAT link, you will encounter some performance issues if you rely on default TCP/IP parameters. By optimizing your VSAT link, you can significantly improve response times when accessing Internet hosts.

TCP/IP factors over a satellite connection A VSAT is often referred to as a long fat pipe network. This term refers to factors that affect TCP/IP performance on any network that has relatively large bandwidth, but high latency. Most Internet connections in Africa and other parts of the developing world are via VSAT. Therefore, even if a university gets its connection via an ISP, this section might apply if the ISP's connection is via VSAT. The high latency in satellite networks is due to the long distance to the satellite and the constant speed of light. This distance adds about 520 ms to a packets round-trip time (RTT), compared to a typical RTT between Europe and the USA of about 140 ms.

Due to the speed of light and long distances involved, a single ping packet can take more than 520 ms to be acknowledged over a VSAT link. The factors that most significantly impact TCP/IP performance are long RTT, large bandwidth delay product, and transmission errors. Generally speaking, operating systems that support modern TCP/IP implementations should be used in a satellite network. These implementations support the RFC 1323 extensions: The window scale option for supporting large TCP window sizes (larger than 64KB). Selective acknowledgment (SACK) to enable faster recovery from transmission errors. Timestamps for calculating appropriate RTT and retransmission timeout values for the link in use.

Long round-trip time (RTT) Satellite links have an average RTT of around 520ms to the first hop. TCP uses the slow-start mechanism at the start of a connection to find the appropriate TCP/IP parameters for that connection. Time spent in the slow-start stage is proportional to the RTT, and for a satellite link it means that TCP stays in slow-start mode for a longer time than would otherwise be the case. This drastically decreases the throughput of short-duration TCP connections. This is can be seen in the way that a small website might take surprisingly long to load, but when a large file is transferred acceptable data rates are achieved after a while. Furthermore, when packets are lost,

TCP enters the congestion-control phase, and owing to the higher RTT, remains in this phase for a longer time, thus reducing the throughput of both short- and long-duration TCP connections.

Large bandwidth-delay product The amount of data in transit on a link at any point of time is the product of bandwidth and the RTT. Because of the high latency of the satellite link, the bandwidth-delay product is large. TCP/IP allows the remote host to send a certain amount of data in advance without acknowledgment. An acknowledgment is usually required for all incoming data on a TCP/IP connection. However, the remote host is always allowed to send a certain amount of data without acknowledgment, which is important to achieve a good transfer rate on large bandwidth delay product connections. This amount of data is called the TCP window size. The window size is usually 64KB in modern TCP/IP implementations. On satellite networks, the value of the bandwidth-delay product is important. To utilize the link fully, the window size of the connection should be equal to the bandwidth-delay product. If the largest window size allowed is 64KB, the maximum theoretical throughput achievable via satellite is (window size) / RTT, or 64KB / 520 ms. This gives a maximum data rate of 123 KB/s, which is 984 kbps, regardless of the fact that the capacity of the link may be much greater. Each TCP segment header contains a field called advertised window, which specifies how many additional bytes of data the receiver is prepared to accept. The advertised window is the receiver's current available buffer size. The sender is not allowed to send more bytes than the advertised window. To maximize performance, the sender should set its send buffer size and the receiver should set its receive buffer size to no less than the bandwidth-delay product. This buffer size has a maximum value of 64KB in most modern TCP/IP implementations. To overcome the problem of TCP/IP stacks from operating systems that don't increase the window size beyond 64KB, a technique known as TCP acknowledgment spoofing can be used (see Performance Enhancing Proxy, below).

Transmission errors In older TCP/IP implementations, packet loss is always considered to have been caused by congestion (as opposed to link errors). When this happens, TCP performs congestion avoidance, requiring three duplicate ACKs or slow start in the case of a timeout. Because of the long RTT value, once this congestion-control phase is started, TCP/IP on satellite links will take a longer time to return to the previous throughput level. Therefore errors on a satellite link have a more serious effect on the performance of TCP than over low latency links. To overcome this limitation, mechanisms such as Selective Acknowledgment (SACK) have been developed. SACK specifies exactly those packets that have been received, allowing the sender to retransmit only those segments that are missing because of link errors. The Microsoft Windows 2000 TCP/IP Implementation Details White Paper states "Windows 2000 introduces support for an important performance feature known as Selective Acknowledgment (SACK). SACK is especially important for connections using large TCP window sizes." SACK has been a standard feature in Linux and BSD kernels for quite some time. Be sure that your Internet router and your ISPs remote side both support SACK. Implications for

universities If a site has a 512 kbps connection to the Internet, the default TCP/IP settings are likely sufficient, because a 64 KB window size can fill up to 984 kbps. But if the university has more than 984 kbps, it might in some cases not get the full bandwidth of the available link due to the "long fat pipe network" factors discussed above. What these factors really imply is that they prevent a single machine from filling the entire bandwidth. This is not a bad thing during the day, because many people are using the bandwidth. But if, for example, there are large scheduled downloads at night, the administrator might want those downloads to make use of the full bandwidth, and the "long fat pipe network" factors might be an obstacle. This may also become critical If a significant amount of your network traffic routes through a single tunnel or VPN connection to the other end of the VSAT link. Administrators might consider taking steps to ensure that the full bandwidth can be achieved by tuning their TCP/IP settings. If a university has implemented a network where all traffic has to go through the proxy (enforced by network layout), then the only machines that make connections to the Internet will be the proxy and mail servers. For more information, see http://www.psc.edu/networking/perf_tune.html .

Performance-enhancing proxy (PEP) The idea of a Performance-enhancing proxy is described in RFC 3135 (see http://www.ietf.org/rfc/rfc3135), and would be a proxy server with a large disk cache that has RFC 1323 extensions, among other features. A laptop has a TCP session with the PEP at the ISP. That PEP, and the one at the satellite provider, communicates using a different TCP session or even their own proprietary protocol. The PEP at the satellite provider gets the files from the web server. In this way, the TCP session is split, and thus the link characteristics that affect protocol performance (long fat pipe factors) are overcome (by TCP acknowledgment spoofing, for example). Additionally, the PEP makes use of proxying and pre-fetching to accelerate web access further. Such a system can be built from scratch using Squid, for example, or purchased "off the shelf" from a number of vendors.

More information While bandwidth optimization is a complex and often difficult subject, the techniques in this chapter should help reduce obvious sources of wasted bandwidth. To make the best possible use of available bandwidth, you will need to define a good access policy, set up comprehensive monitoring and analysis tools, and implement a network architecture that enforces desired usage limits. For more information about bandwidth optimization, see the free book How to Accelerate Your Internet (http://bwmo.net/): http://bwmo.net/pdf/bwmo-ebook.pdf

Antennas & Transmission Lines


The transmitter that generates the RF power to drive the antenna is usually located at some distance from the antenna terminals. The connecting link between the two is the RF transmission line. Its purpose is to carry RF power from one place to another, and to do this as efficiently as possible. From the receiver side, the antenna is responsible for picking up any radio signals in the air and passing them to the receiver with the minimum amount of distortion, so that the radio has its best chance to decode the signal. For these reasons, the RF cable has a very important role in radio systems: it must maintain the integrity of the signals in both directions. There are two main categories of transmission lines: cables and waveguides. Both types work well for efficiently carrying RF power at 2.4GHz.

Cables RF cables are, for frequencies higher than HF, almost exclusively coaxial cables (or coax for short, derived from the words of common axis). Coax cables have a core conductor wire surrounded by a non-conductive material called dielectric, or simply insulation. The dielectric is then surrounded by an encompassing shielding which is often made of braided wires. The dielectric prevents an electrical connection between the core and the shielding. Finally, the coax is protected by an outer casing which is generally made from a PVC material. The inner conductor carries the RF signal, and the outer shield prevents the RF signal from radiating to the atmosphere, and also prevents outside signals from interfering with the signal carried by the core. Another interesting fact is that high frequency electrical signal always travels along the outer layer of a conductor: the larger the central conductor, the better signal will flow. This is called the skin effect.

Coaxial cable with jacket, shield, dielectric, and core conductor. Even though the coaxial construction is good at containing the signal on the core wire, there is some resistance to the electrical flow: as the signal travels down the core, it will fade away. This fading is known as attenuation, and for transmission lines it is measured in decibels per meter (dB/m). The rate of attenuation is a function of the signal frequency and the physical

construction of the cable itself. As the signal frequency increases, so does its attenuation. Obviously, we need to minimize the cable attenuation as much as possible by keeping the cable very short and using high quality cables. Here are some points to consider when choosing a cable for use with microwave devices: 1. The shorter the better! The first rule when you install a piece of cable is to try to keep it as short as possible. The power loss is not linear, so doubling the cable length means that you are going to lose much more than twice the power. In the same way, reducing the cable length by half gives you more than twice the power at the antenna. The best solution is to place the transmitter as close as possible to the antenna, even when this means placing it on a tower. 2. The cheaper the worse! The second golden rule is that any money you invest in buying a good quality cable is a bargain. Cheap cables are intended to be used at low frequencies, such as VHF. Microwaves require the highest quality cables available. All other options are nothing but a dummy load. Note: A dummy load is a device that dissipates RF energy without radiating it. Think of it as a heat sink that works at radio frequencies. 3. Always avoid RG-58. It is intended for thin Ethernet networking, CB or VHF radio, not for microwave. 4. Always avoid RG-213. It is intended for CB and HF radio. In this case the cable diameter does not imply a high quality, or low attenuation. 5. Whenever possible, use Heliax (also called Foam) cables for connecting the transmitter to the antenna. When Heliax is unavailable, use the best rated LMR cable you can find. Heliax cables have a solid or tubular center conductor with a corrugated solid outer conductor to enable them to flex. Heliax can be built in two ways, using either air or foam as a dielectric. Air dielectric Heliax is the most expensive and guarantees the minimum loss, but it is very difficult to handle. Foam dielectric Heliax is slightly more lossy, but is less expensive and easier to install. A special procedure is required when soldering connectors in order to keep the foam dielectric dry and uncorrupted. LMR is a brand of coax cable available in various diameters that works well at microwave frequencies. LMR-400 and LMR-600 are a commonly used alternative to Heliax. 6. Whenever possible, use cables that are pre-crimped and tested in a proper lab. Installing connectors to cable is a tricky business, and is difficult to do properly even with the proper tools. Unless you have access to equipment that can verify a cable you make yourself (such as a spectrum analyzer and signal generator, or time domain reflectometer), troubleshooting a network that uses homemade cable can be difficult. 7. Dont abuse your transmission line. Never step over a cable, bend it too much, or try to unplug a connector by pulling directly the cable. All of those behaviors may change the mechanical characteristic of the cable and therefore its impedance, short the inner conductor to the shield, or even break the line. Those problems are difficult to track and recognize and can lead to unpredictable behavior on the radio link.

Waveguides Above 2 GHz, the wavelength is short enough to allow practical, efficient energy transfer by different means. A waveguide is a conducting tube through which energy is transmitted in the form of electromagnetic waves. The tube acts as a boundary that confines the waves in the enclosed space. The Faraday cage effect prevents electromagnetic effects from being evident outside the guide. The electromagnetic fields are propagated through the waveguide by means of reflections against its inner walls, which are considered perfect conductors. The intensity of the fields is greatest at the center along the X dimension, and must diminish to zero at the end walls because the existence of any field parallel to the walls at the surface would cause an infinite current to flow in a perfect conductor. Waveguides, of course, cannot carry RF in this fashion. The X, Y and Z dimensions of a rectangular waveguide can be seen in the following figure:

The X, Y, and Z dimensions of a rectangular waveguide There are an infinite number of ways in which the electric and magnetic fields can arrange themselves in a waveguide for frequencies above the low cutoff frequency. Each of these field configurations is called a mode. The modes may be separated into two general groups. One group, designated TM (Transverse Magnetic), has the magnetic field entirely transverse to the direction of propagation, but has a component of the electric field in the direction of propagation. The other type, designated TE (Transverse Electric) has the electric field entirely transverse, but has a component of magnetic field in the direction of propagation. The mode of propagation is identified by the group letters followed by two subscript numerals. For example, TE 10, TM 11, etc. The number of possible modes increases with the frequency for a given size of guide, and there is only one possible mode, called the dominant mode, for the lowest frequency that can be transmitted. In a rectangular guide, the critical dimension is X. This dimension must be more than 0.5 at the lowest frequency to be transmitted. In practice, the Y dimension usually is made about equal to 0.5 X to avoid the possibility of operation in other than the dominant mode. Cross-sectional shapes other than the rectangle can be used, the most important being the circular pipe. Much the same considerations apply as in the rectangular case. Wavelength dimensions for rectangular and circular guides are given in the following table, where X is the width of a rectangular guide and r is the radius of a circular guide. All figures apply to the dominant mode.

Type of guide Cutoff wavelength Longest wavelength transmitted with littleattenuation Shortest wavelength before next mode becomes possible

Rectangular 2X 1.6X 1.1X

Circular 3.41r 3.2r 2.8r

Energy may be introduced into or extracted from a waveguide by means of either an electric or magnetic field. The energy transfer typically happens through a coaxial line. Two possible methods for coupling to a coaxial line are using the inner conductor of the coaxial line, or through a loop. A probe which is simply a short extension of the inner conductor of the coaxial line can be oriented so that it is parallel to the electric lines of force. A loop can be arranged so that it encloses some of the magnetic lines of force. The point at which maximum coupling is obtained depends upon the mode of propagation in the guide or cavity. Coupling is maximum when the coupling device is in the most intense field. If a waveguide is left open at one end, it will radiate energy (that is, it can be used as an antenna rather than as a transmission line). This radiation can be enhanced by flaring the waveguide to form a pyramidal horn antenna. We will see an example of a practical waveguide antenna for Wi-Fi later in this section. Cable Type RG-58 RG-213 LMR-400 3/8 LDF Core 0.9 mm 2.26 mm 2.74 mm 3.1 mm Dielectric 2.95 mm 7.24 mm 7.24 mm 8.12 mm Shield 3.8 mm 8.64 mm 8.13 mm 9.7 mm Jacket 4.95 mm 10.29 mm 10.29 mm 11 mm

Here is a table contrasting the sizes of various common transmission lines. Choose the best cable you can afford with the lowest possible attenuation at the frequency you intend to use for your wireless link.

Connectors and adapters Connectors allow a cable to be connected to another cable or to a component of the RF chain. There are a wide variety of fittings and connectors designed to go with various sizes and types of coaxial lines. We will describe some of the most popular ones. BNC connectors were developed in the late 40s. BNC stands for Bayonet Neill Concelman, named after the men who invented it: Paul Neill and Carl Concelman. The BNC product line is a miniature quick connect / disconnect connector. It features two bayonet lugs on the female connector, and mating is achieved with only a quarter turn of the coupling nut. BNC's are ideally suited for cable termination for miniature to subminiature coaxial cable (RG- 58 to RG-179, RG-

316, etc.) They have acceptable performance up to few GHz. They are most commonly found on test equipment and 10base2 coaxial Ethernet cables. TNC connectors were also invented by Neill and Concelman, and are a threaded variation of the BNC. Due to the better interconnect provided by the threaded connector, TNC connectors work well through about 12GHz. TNC stands for Threaded Neill Concelman. Type N (again for Neill, although sometimes attributed to Navy) connectors were originally developed during the Second World War. They are usable up to 18 Ghz, and very commonly used for microwave applications. They are available for almost all types of cable. Both the plug / cable and plug / socket joints are waterproof, providing an effective cable clamp. SMA is an acronym for SubMiniature version A, and was developed in the 60s. SMA connectors are precision, subminiature units that provide excellent electrical performance up to 18 GHz. These high-performance connectors are compact in size and mechanically have outstanding durability. The SMB name derives from SubMiniature B, and it is the second subminiature design. The SMB is a smaller version of the SMA with snap-on coupling. It provides broadband capability through 4 GHz with a snap-on connector design. MCX connectors were introduced in the 80s. While the MCX uses identical inner contact and insulator dimensions as the SMB, the outer diameter of the plug is 30% smaller than the SMB. This series provides designers with options where weight and physical space are limited. MCX provides broadband capability though 6 GHz with a snap-on connector design. In addition to these standard connectors, most WiFi devices use a variety of proprietary connectors. Often, these are simply standard microwave connectors with the center conductor parts reversed, or the thread cut in the opposite direction. These parts are often integrated into a microwave system using a short jumper called a pigtail that converts the non-standard connector into something more robust and commonly available. Some of these connectors include: RP-TNC. This is a TNC connector with the genders reversed. These are most commonly found on Linksys equipment, such as the WRT54G. U.FL (also known as MHF). The U.FL is a patented connector made by Hirose, while the MHF is a mechanically equivalent connector. This is possibly the smallest microwave connector currently in wide use. The U.FL / MHF is typically used to connect a mini-PCI radio card to an antenna or larger connector (such as an N or TNC). The MMCX series, which is also called a MicroMate, is one of the smallest RF connector line and was developed in the 90s. MMCX is a micro-miniature connector series with a lock-snap mechanism allowing for 360 degrees rotation enabling flexibility. MMCX connectors are commonly found on PCMCIA radio cards, such as those manufactured by Senao and Cisco. MC-Card connectors are even smaller and more fragile than MMCX. They have a split outer connector that breaks easily after just a few interconnects. These are commonly found on Lucent

/ Orinoco / Avaya equipment. Adapters, which are also called coaxial adapters, are short, twosided connectors which are used to join two cables or components which cannot be connected directly. Adapters can be used to interconnect devices or cables with different types. For example, an adapter can be used to connect an SMA connector to a BNC. Adapters may also be used to fit together connectors of the same type, but which cannot be directly joined because of their gender.

An N female barrel adapter. For example a very useful adapter is the one which enables to join two Type N connectors, having socket (female) connectors on both sides.

Choosing the proper connector 1. The gender question. Virtually all connectors have a well defined gender consisting of either a pin (the male end) or a socket (the female end). Usually cables have male connectors on both ends, while RF devices (i.e. transmitters and antennas) have female connectors. Devices such as directional couplers and line-through measuring devices may have both male and female connectors. Be sure that every male connector in your system mates with a female connector. 2. Less is best! Try to minimize the number of connectors and adapters in the RF chain. Each connector introduces some additional loss (up to a few dB for each connection, depending on the connector!) 3. Buy, dont build! As mentioned earlier, buy cables that are already terminated with the connectors you need whenever possible. Soldering connectors is not an easy task, and to do this job properly is almost impossible for small connectors as U.FL and MMCX. Even terminating Foam cables is not an easy task. 4. Dont use BNC for 2.4GHz or higher. Use N type connectors (or SMA, SMB, TNC, etc.) 5. Microwave connectors are precision-made parts, and can be easily damaged by mistreatment. As a general rule, you should rotate the outer sleeve to tighten the connector, leaving the rest of the connector (and cable) stationary. If other parts of the connector are twisted while tightening or loosening, damage can easily occur.

6. Never step over connectors, or drop connectors on the floor when disconnecting cables (this happens more often than what you may imagine, especially when working on a mast over a roof). 7. Never use tools like pliers to tighten connectors. Always use your hands. When working outside, remember that metals expand at high temperatures and reduce their size at low temperatures: a very tightened connector in the summer can bind or even break in winter.

Antennas & radiation patterns Antennas are a very important component of communication systems. By definition, an antenna is a device used to transform an RF signal traveling on a conductor into an electromagnetic wave in free space. Antennas demonstrate a property known as reciprocity, which means that an antenna will maintain the same characteristics regardless if whether it is transmitting or receiving. Most antennas are resonant devices, which operate efficiently over a relatively narrow frequency band. An antenna must be tuned to the same frequency band of the radio system to which it is connected, otherwise the reception and the transmission will be impaired. When a signal is fed into an antenna, the antenna will emit radiation distributed in space in a certain way. A graphical representation of the relative distribution of the radiated power in space is called a radiation pattern.

Antenna term glossary Before we talk about specific antennas, there are a few common terms that must be defined and explained: Input Impedance For an efficient transfer of energy, the impedance of the radio, antenna, and transmission cable connecting them must be the same. Transceivers and their transmission lines are typically designed for 50 impedance. If the antenna has impedance different than 50, then there is a mismatch and an impedance matching circuit is required. When any of these components are mismatched, transmission efficiency suffers.

Return loss Return loss is another way of expressing mismatch. It is a logarithmic ratio measured in dB that compares the power reflected by the antenna to the power that is fed into the antenna from the transmission line. The relationship between SWR and return loss is the following: SWR Return Loss (dalam dB) = 20log 10 ---------------SWR-1

While some energy will always be reflected back into the system, a high return loss will yield unacceptable antenna performance. Bandwidth The bandwidth of an antenna refers to the range of frequencies over which the antenna can operate correctly. The antenna's bandwidth is the number of Hz for which the antenna will exhibit an SWR less than 2:1. The bandwidth can also be described in terms of percentage of the center frequency of the band. F H - FL Bandwidth = 100 -------------------FC ...where FH is the highest frequency in the band, FL is the lowest frequency in the band, and FC is the center frequency in the band. In this way, bandwidth is constant relative to frequency. If bandwidth was expressed in absolute units of frequency, it would be different depending upon the center frequency. Different types of antennas have different bandwidth limitations.

Directivity and Gain Directivity is the ability of an antenna to focus energy in a particular direction when transmitting, or to receive energy from a particular direction when receiving. If a wireless link uses fixed locations for both ends, it is possible to use antenna directivity to concentrate the radiation beam in the wanted direction. In a mobile application where the transceiver is not fixed, it may be impossible to predict where the transceiver will be, and so the antenna should ideally radiate as well as possible in all directions. An omnidirectional antenna is used in these applications. Gain is not a quantity which can be defined in terms of a physical quantity such as the Watt or the Ohm, but it is a dimensionless ratio. Gain is given in reference to a standard antenna. The two most common reference antennas are the isotropic antenna and the resonant half-wave dipole antenna. The isotropic antenna radiates equally well in all directions. Real isotropic antennas do not exist, but they provide useful and simple theoretical antenna patterns with which to compare real antennas. Any real antenna will radiate more energy in some directions than in others. Since antennas cannot create energy, the total power radiated is the same as an isotropic antenna. Any additional energy radiated in the directions it favors is offset by equally less energy radiated in all other directions. The gain of an antenna in a given direction is the amount of energy radiated in that direction compared to the energy an isotropic antenna would radiate in the same direction when driven with the same input power. Usually we are only interested in the maximum gain, which is the gain in the direction in which the antenna is radiating most of the power. An antenna gain of 3 dB compared to an isotropic antenna would be written as 3 dBi. The resonant half-wave dipole can be a useful standard for comparing to other antennas at one frequency or over a very narrow band of frequencies. To compare the dipole to an antenna over a range of frequencies requires a number of dipoles of different lengths. An antenna gain of 3 dB compared to a dipole antenna would be written as 3 dBd.

The method of measuring gain by comparing the antenna under test against a known standard antenna, which has a calibrated gain, is technically known as a gain transfer technique. Another method for measuring gain is the 3 antennas method, where the transmitted and received power at the antenna terminals is measured between three arbitrary antennas at a known fixed distance. Radiation Pattern The radiation pattern or antenna pattern describes the relative strength of the radiated field in various directions from the antenna, at a constant distance. The radiation pattern is a reception pattern as well, since it also describes the receiving properties of the antenna. The radiation pattern is three dimensional, but usually the measured radiation patterns are a two dimensional slice of the three-dimensional pattern, in the horizontal or vertical planes. These pattern measurements are presented in either a rectangular or a polar format. The following figure shows a rectangular plot presentation of a typical ten-element Yagi. The detail is good but it is difficult to visualize the antenna behavior in different directions.

A rectangular plot of a yagi radiation pattern. Polar coordinate systems are used almost universally. In the polar-coordinate graph, points are located by projection along a rotating axis (radius) to an intersection with one of several concentric circles. The following is a polar plot of the same 10 element Yagi antenna. Polar coordinate systems may be divided generally in two classes: linear and logarithmic. In the linear coordinate system, the concentric circles are equally spaced, and are graduated. Such a grid may be used to prepare a linear plot of the power contained in the signal. For ease of comparison, the equally spaced concentric circles may be replaced with appropriately placed circles representing the decibel response, referenced to 0 dB at the outer edge of the plot. In this kind of plot the minor lobes are suppressed. Lobes with peaks more than 15 dB or so below the main lobe disappear because of their small size. This grid enhances plots in which the antenna has a high directivity and small minor lobes. The voltage of the signal, rather than the power, can also be plotted on a linear coordinate system. In this case, too, the directivity is enhanced and the minor lobes suppressed, but not in the same degree as in the linear power grid.

A linear polar plot of the same yagi. In the logarithmic polar coordinate system the concentric grid lines are spaced periodically according to the logarithm of the voltage in the signal. Different values may be used for the logarithmic constant of periodicity, and this choice will have an effect on the appearance of the plotted patterns. Generally the 0 dB reference for the outer edge of the chart is used. With this type of grid, lobes that are 30 or 40 dB below the main lobe are still distinguishable. The spacing between points at 0 dB and at -3 dB is greater than the spacing between -20 dB and -23 dB, which is greater than the spacing between -50 dB and -53 dB. The spacing thus correspond to the relative significance of such changes in antenna performance. A modified logarithmic scale emphasizes the shape of the major beam while compressing very low-level (>30 dB) sidelobes towards the center of the pattern. This is shown in Figure below. There are two kinds of radiation pattern: absolute and relative. Absolute radiation patterns are presented in absolute units of field strength or power. Relative radiation patterns are referenced in relative units of field strength or power. Most radiation pattern measurements are relative to the isotropic antenna, and the gain transfer method is then used to establish the absolute gain of the antenna.

The logarithmic polar plot The radiation pattern in the region close to the antenna is not the same as the pattern at large distances. The term near-field refers to the field pattern that exists close to the antenna, while the term far-field refers to the field pattern at large distances. The far-field is also called the radiation field, and is what is most commonly of interest. Ordinarily, it is the radiated power that is of interest, and so antenna patterns are usually measured in the far-field region. For pattern measurement it is important to choose a distance sufficiently large to be in the far-field, well out of the near-field. The minimum permissible distance depends on the dimensions of the antenna in relation to the wavelength. The accepted formula for this distance is: 2d2 rmin = -------------

where rmin is the minimum distance from the antenna, d is the largest dimension of the antenna, and is the wavelength.

Beamwidth An antenna's beamwidth is usually understood to mean the half-power beamwidth. The peak radiation intensity is found, and then the points on either side of the peak which represent half the power of the peak intensity are located. The angular distance between the half power points is defined as the beamwidth. Half the power expressed in decibels is -3dB, so the half power beamwidth is sometimes referred to as the 3dB beamwidth. Both horizontal and vertical beamwidth are usually considered. Assuming that most of the radiated power is not divided into

sidelobes, then the directive gain is inversely proportional to the beamwidth: as the beamwidth decreases, the directive gain increases.

Sidelobes No antenna is able to radiate all the energy in one preferred direction. Some is inevitably radiated in other directions. These smaller peaks are referred to as sidelobes, commonly specified in dB down from the main lobe.

Nulls In an antenna radiation pattern, a null is a zone in which the effective radiated power is at a minimum. A null often has a narrow directivity angle compared to that of the main beam. Thus, the null is useful for several purposes, such as suppression of interfering signals in a given direction.

Polarization Polarization is defined as the orientation of the electric field of an electromagnetic wave. Polarization is in general described by an ellipse. Two special cases of elliptical polarization are linear polarization and circular polarization.The initial polarization of a radio wave is determined by the antenna.

The electrical wave is perpendicular to magnetic wave, both of which are perpendicular to the direction of propagation. With linear polarization, the electric field vector stays in the same plane all the time. The electric field may leave the antenna in a vertical orientation, a horizontal orientation, or at some angle between the two. Vertically polarized radiation is somewhat less affected by reflections over the transmission

path. Omnidirectional antennas always have vertical polarization. With horizontal polarization, such reflections cause variations in received signal strength. Horizontal antennas are less likely to pick up man-made interference, which ordinarily is vertically polarized. In circular polarization the electric field vector appears to be rotating with circular motion about the direction of propagation, making one full turn for each RF cycle. This rotation may be right-hand or left-hand. Choice of polarization is one of the design choices available to the RF system designer.

Polarization Mismatch In order to transfer maximum power between a transmit and a receive antenna, both antennas must have the same spatial orientation, the same polarization sense, and the same axial ratio. When the antennas are not aligned or do not have the same polarization, there will be a reduction in power transfer between the two antennas. This reduction in power transfer will reduce the overall system efficiency and performance. When the transmit and receive antennas are both linearly polarized, physical antenna misalignment will result in a polarization mismatch loss, which can be determined using the following formula: ...where is the difference in alignment angle between the two antennas. For 15 the loss is approximately 0.3dB, for 30 we lose 1.25dB, for 45 we lose 3dB and for 90 we have an infinite loss. In short, the greater the mismatch in polarization between a transmitting and receiving antenna, the greater the apparent loss. In the real world, a 90 mismatch in polarization is quite large but not infinite. Some antennas, such as yagis or can antennas, can be simply rotated 90 to match the polarization of the other end of the link. You can use the polarization effect to your advantage on a point-to-point link. Use a monitoring tool to observe interference from adjacent networks, and rotate one antenna until you see the lowest received signal. Then bring your link online and orient the other end to match polarization. This technique can sometimes be used to build stable links, even in noisy radio environments. Front-to-back ratio It is often useful to compare the front-to-back ratio of directional antennas. This is the ratio of the maximum directivity of an antenna to its directivity in the opposite direction. For example, when the radiation pattern is plotted on a relative dB scale, the front-to-back ratio is the difference in dB between the level of the maximum radiation in the forward direction and the level of radiation at 180 degrees. This number is meaningless for an omnidirectional antenna, but it gives you an idea of the amount of power directed forward on a very directional antenna. Loss (dB) = 20 log (cos )

Types of Antennas A classification of antennas can be based on: Frequency and size. Antennas used for HF are different from antennas used for VHF, which in turn are different from antennas for microwave. The wavelength is different at different frequencies, so the antennas must be different in size to radiate signals at the correct wavelength. We are particularly interested in antennas working in the microwave range, especially in the 2.4 GHz and 5 GHz frequencies. At 2.4 GHz the wavelength is 12.5 cm, while at 5 GHz it is 6 cm. Directivity. Antennas can be omnidirectional, sectorial or directive. Omnidirectional antennas radiate roughly the same pattern all around the antenna in a complete 360 pattern. The most popular types of omnidirectional antennas are the dipole and the ground plane. Sectorial antennas radiate primarily in a specific area. The beam can be as wide as 180 degrees, or as narrow as 60 degrees. Directional or directive antennas are antennas in which the beamwidth is much narrower than in sectorial antennas. They have the highest gain and are therefore used for long distance links. Types of directive antennas are the Yagi, the biquad, the horn, the helicoidal, the patch antenna, the parabolic dish, and many others. Physical construction. Antennas can be constructed in many different ways, ranging from simple wires, to parabolic dishes, to coffee cans. When considering antennas suitable for 2.4 GHz WLAN use, another classification can be used: Application. Access points tend to make point-to-multipoint networks, while remote links are point-to-point. Each of these suggests different types of antennas for their purpose. Nodes that are used for multipoint access will likely use omni antennas which radiate equally in all directions, or sectorial antennas which focus into a small area. In the point-to-point case, antennas are used to connect two single locations together. Directive antennas are the primary choice for this application. A brief list of common type of antennas for the 2.4 GHz frequency is presented now, with a short description and basic information about their characteristics.

1/4 wavelength ground plane The 14 wavelength ground plane antenna is very simple in its construction and is useful for communications when size, cost and ease of construction are important. This antenna is designed to transmit a vertically polarized signal. It consists of a 14 wave element as half-dipole and three or four 14 wavelength ground elements bent 30 to 45 degrees down. This set of elements, called radials, is known as a ground plane.

Quarter wavelength ground plane antenna This is a simple and effective antenna that can capture a signal equally from all directions. To increase the gain, the signal can be flattened out to take away focus from directly above and below, and providing more focus on the horizon. The vertical beamwidth represents the degree of flatness in the focus. This is useful in a Point-to-Multipoint situation, if all the other antennas are also at the same height. The gain of this antenna is in the order of 2 4 dBi.

Yagi antenna A basic Yagi consists of a certain number of straight elements, each measuring approximately half wavelength. The driven or active element of a Yagi is the equivalent of a center-fed, halfwave dipole antenna. Parallel to the driven element, and approximately 0.2 to 0.5 wavelength on either side of it, are straight rods or wires called reflectors and directors, or simply passive elements. A reflector is placed behind the driven element and is slightly longer than half wavelength; a director is placed in front of the driven element and is slightly shorter than half wavelength. A typical Yagi has one reflector and one or more directors. The antenna propagates electromagnetic field energy in the direction running from the driven element toward the directors, and is most sensitive to incoming electromagnetic field energy in this same direction. The more directors a Yagi has, the greater the gain. As more directors are added to a Yagi, it therefore becomes longer. Following is the photo of a Yagi antenna with 6 directors and one reflector.

A Yagi antenna Yagi antennas are used primarily for Point-to-Point links, have a gain from 10 to 20 dBi and a horizontal beamwidth of 10 to 20 degrees.

Horn The horn antenna derives its name from the characteristic flared appearance. The flared portion can be square, rectangular, cylindrical or conical. The direction of maximum radiation corresponds with the axis of the horn. It is easily fed with a waveguide, but can be fed with a coaxial cable and a proper transition.

Feed horn made from a food can Horn antennas are commonly used as the active element in a dish antenna. The horn is pointed toward the center of the dish reflector. The use of a horn, rather than a dipole antenna or any other type of antenna, at the focal point of the dish minimizes loss of energy around the edges of the dish reflector. At 2.4 GHz, a simple horn antenna made with a tin can has a gain in the order of 10 - 15 dBi.

Parabolic Dish Antennas based on parabolic reflectors are the most common type of directive antennas when a high gain is required. The main advantage is that they can be made to have gain and directivity as large as required. The main disadvantage is that big dishes are difficult to mount and are likely to have a large windage.

A solid dish antenna Dishes up to one meter are usually made from solid material. Aluminum is frequently used for its weight advantage, its durability and good electrical characteristics. Windage increases rapidly with dish size and soon becomes a severe problem. Dishes which have a reflecting surface that uses an open mesh are frequently used. These have a poorer front-to-back ratio, but are safer to use and easier to build. Copper, aluminum, brass, galvanized steel and iron are suitable mesh materials.

BiQuad The BiQuad antenna is simple to build and offers good directivity and gain for Point-to-Point communications. It consists of a two squares of the same size of 14 wavelength as a radiating element and of a metallic plate or grid as reflector. This antenna has a beamwidth of about 70 degrees and a gain in the order of 10-12 dBi. It can be used as stand-alone antenna or as feeder for a Parabolic Dish. The polarization is such that looking at the antenna from the front, if the squares are placed side by side the polarization is vertical.

The BiQuad.

Other Antennas Many other types of antennas exist and new ones are created following the advances in technology. Sector or Sectorial antennas: they are widely used in cellular telephony infrastructure and are usually built adding a reflective plate to one or more phased dipoles. Their horizontal beamwidth can be as wide as 180 degrees, or as narrow as 60 degrees, while the vertical is usually much narrower. Composite antennas can be built with many Sectors to cover a wider horizontal range (multisectorial antenna). Panel or Patch antennas: they are solid flat panels used for indoor coverage, with a gain up to 20 dB.

Reflector theory The basic property of a perfect parabolic reflector is that it converts a spherical wave irradiating from a point source placed at the focus into a plane wave. Conversely, all the energy received by the dish from a distant source is reflected to a single point at the focus of the dish. The position of the focus, or focal length, is given by: D2 f = ----------16 c ...where D is the dish diameter and c is the depth of the parabola at its center. The size of the dish is the most important factor since it determines the maximum gain that can be achieved at the given frequency and the resulting beamwidth. The gain and beamwidth obtained are given by: ( x D)2 Gain = ----------- n 2 70 Beamwidth = --------D ...where D is the dish diameter and n is the efficiency. The efficiency is determined mainly by the effectiveness of illumination of the dish by the feed, but also by other factors. Each time the diameter of a dish is doubled, the gain is four times, or 6 dB, greater. If both stations double the size of their dishes, signal strength can be increased of 12 dB, a very substantial gain. An efficiency of 50% can be assumed when hand-building the antenna. The ratio f / D (focal length/diameter of the dish) is the fundamental factor governing the design of the feed for a dish. The ratio is directly related to the beamwidth of the feed necessary to illuminate the dish effectively. Two dishes of the same diameter but different focal lengths require different design of feed if both are to be illuminated efficiently. The value of 0.25 corresponds to the common focal-plane dish in which the focus is in the same plane as the rim of the dish.

Amplifiers As mentioned earlier, antennas do not actually create power. They simply direct all available power into a particular pattern. By using a power amplifier, you can use DC power to augment your available signal. An amplifier connects between the radio transmitter and the antenna, and has an additional lead that connects to a power source. Amplifiers are available that work at 2.4GHz, and can add several Watts of power to your transmission. These devices sense when an attached radio is transmitting, and quickly power up and amplify the signal. They then switch off again when transmission ends. When receiving, they also add amplification to the signal before sending it to the radio. Unfortunately, simply adding amplifiers will not magically solve all of your networking problems. We do not discuss power amplifiers at length in this guide because there are a number of significant drawbacks to using them:

They are expensive. Amplifiers must work at relatively wide bandwidths at 2.4 GHz, and must switch quickly enough to work for Wi-Fi applications. These amplifiers do exist, but they tend to cost several hundred dollars per unit. You will need at least two. Whereas antennas provide reciprocal gain that benefits both sides of a connection, amplifiers work best at amplifying a transmitted signal. If you only add an amplifier to one end of a link with insufficient antenna gain, it will likely be able to be heard but will not be able to hear the other end. They provide no additional directionality. Adding antenna gain provides both gain and directionality benefits to both ends of the link. They not only improve the available amount of signal, but tend to reject noise from other directions. Amplifiers blindly amplify both desired and interfering signals, and can make interference problems worse. Amplifiers generate noise for other users of the band. By increasing your output power, you are creating a louder source of noise for other users of the unlicensed band. This may not be much of an issue today in rural areas, but it can cause big problems in populated areas. Conversely, adding antenna gain will improve your link and can actually decrease the noise level for your neighbors. Using amplifiers probably isnt legal. Every country imposes power limits on use of unlicensed spectrum. Adding an antenna to a highly amplified signal will likely cause the link to exceed legal limits. Using amplifiers is often compared to the inconsiderate neighbor who wants to listen to the radio outside their home, and so turns it up to full volume. They might even improve reception by pointing their speakers out the window. While they may now be able to hear the radio, so must everyone else on the block. This approach may scale to exactly one user, but what happens when the neighbors decide to do the same thing with their radios? Using amplifiers for a wireless link causes roughly the same effect at 2.4 GHz. Your link may work better for the moment, but you will have problems when other users of the band decide to use amplifiers of their own. By using higher gain antennas rather than amplifiers, you avoid all of these problems. Antennas cost far less than amps, and can improve a link simply by changing the antenna on one end. Using more sensitive radios and good quality cable also helps significantly on long distance shots. These techniques are unlikely to cause problems for other users of the band, and so we recommend pursuing them before adding amplifiers.

Practical antenna designs The cost of 2.4 GHz antennas has fallen dramatically since the introduction of 802.11b. Innovative designs use simpler parts and fewer materials to achieve impressive gain with relatively little machining. Unfortunately, availability of good antennas is still limited in many areas of the world, and importing them can be prohibitively expensive. While actually designing an antenna can be a complex and error-prone process, constructing antennas from locally available components is very straightforward, and can be a lot of fun. We present four practical antenna designs that can be built for very little money.

USB dongle as dish feed


Possibly the simplest antenna design is the use of a parabola to direct the output of a USB wireless device (known in networking circles as a USB dongle). By placing the internal dipole antenna present in USB wireless dongles at the focus of a parabolic dish, you can provide significant gain without the need to solder or even open the wireless device itself. Many kinds of parabolic dishes will work, including satellite dishes, television antennas, and even metal cookware (such as a wok, round lid, or strainer). As a bonus, inexpensive and lossless USB cable is then used to feed the antenna, eliminating the need for expensive coaxial cable or Heliax. To build a USB dongle parabolic, you will need to find the orientation and location of the dipole inside the dongle. Most devices orient the dipole to be parallel with the short edge of the dongle, but some will mount the dipole perpendicular to the short edge. You can either open the dongle and look for yourself, or simply try the dongle in both positions to see which provides more gain. To test the antenna, point it at an access point several meters away, and connect the USB dongle to a laptop. Using the laptops client driver or a tool such as Netstumbler , observe the received signal strength of the access point. Now, slowly move the dongle in relation to the parabolic while watching the signal strength meter. You should see a significant improvement in gain (20 dB or more) when you find the proper position. The proper position will vary depending on the shape of the parabola and the construction of the USB dongle. Try various positions while watching your signal strength meter until you find the optimum location. Once the best location is found, securely fix the dongle in place. You will need to waterproof the dongle and cable if the antenna is used outdoors. Use a silicone compound or a piece of PVC tubing to seal the electronics against the weather. Many USB-fed parabolic designs and ideas are documented online at http://www.usbwifi.orcon.net.nz/ .

Collinear omni This antenna is very simple to build, requiring just a piece of wire, an N socket and a square metallic plate. It can be used for indoor or outdoor pointto-multipoint short distance coverage. The plate has a hole drilled in the mid dle to accommodate an N type chassis socket that is screwed into place. The wire is soldered to the center pin of the N socket and has coils to separate the active phased elements. Two versions of the antenna are possible: one with two phased elements and two coils and another with four phased elements and four coils. For the short antenna the gain will be around 5dBi, while the long one with four elements will have 7 to 9 dBi of gain. We are going to describe how to build the long antenna only.

Parts list and tools required One screw-on N-type female connector 50 cm of copper or brass wire of 2 mm of diameter 10x10 cm or greater square metallic plate

10 cm x 10 cm aluminum plate. Ruler Pliers File Soldering iron and solder Drill with a set of bits for metal (including a 1.5 cm diameter bit) A piece of pipe or a drill bit with a diameter of 1 cm Vice or clamp Hammer Spanner or monkey wrench

Construction 1. Straighten the wire using the vice.

Make the wire as straight as you can.

2. With a marker, draw a line at 2.5 cm starting from one end of the wire. On this line, bend the wire at 90 degrees with the help of the vice and of the hammer.

Gently tap the wire to make a sharp bend. 3. Draw another line at a distance of 3.6 cm from the bend. Using the vice and the hammer, bend once again the wire over this second line at 90 degrees, in the opposite direction to the first bend but in the same plane.The wire should look like a Z.

Bend the wire into a Z shape 4. We will now twist the Z portion of the wire to make a coil with a diameter of 1 cm. To do this, we will use the pipe or the drill bit and curve the wire around it, with the help of the vice and of the pliers.

Bend the wire around the drill bit to make a coil.

The coil will look like this:

The completed coil 5. You should make a second coil at a distance of 7.8 cm from the first one. Both coils should have the same turning direction and should be placed on the same side of the wire. Make a third and a fourth coil following the same procedure, at the same distance of 7.8 cm one from each other.Trim the last phased element at a distance of 8.0 cm from the fourth coil.

Try to keep it as straight possible. If the coils have been made correctly, it should now be possible to insert apipe through all the coils as shown.

Inserting a pipe can help to straighten the wire. 6. With a marker and a ruler, draw the diagonals on the metallic plate, finding its center. With a small diameter drill bit, make a pilot hole at the center of the plate. Increase the diameter of the hole using bits with an increasing diameter.

Drilling the hole in the metal plate.

The N connector should fit snugly in the hole. 7. To have an antenna impedance of 50 Ohms, it is important that the visible surface of the internal insulator of the connector (the white area around the central pin) is at the same level as the surface of the plate. For this reason, cut 0.5 cm of copper pipe with an external diameter of 2 cm, and place it between the connector and the plate.

Adding a copper pipe spacer helps to match the impedance of the antenna to 50 Ohms. 8. Screw the nut to the connector to fix it firmly on the plate using the spanner.

Secure the N connector tightly to the plate

9. Smooth with the file the side of the wire which is 2.5 cm long, from the first coil. Tin the wire for around 0.5 cm at the smoothed end helping yourself with the vice.

Add a little solder to the end of the wire to tin it prior to soldering. 10. With the soldering iron, tin the central pin of the connector. Keeping the wire vertical with the pliers, solder its tinned side in the hole of the central pin. The first coil should be at 3.0 cm from the plate.

The first coil should start 3.0 cm from the surface of the plate 11. We are now going to stretch the coils extending the total vertical length of the wire. Using the use the vice and the pliers, you should pull the cable so that the final length of the coil is of 2.0 cm.

Stretching the coils. Be very gentle and try not to scrape the surface of the wire with the pliers.

12. Repeat the same procedure for the other three coils, stretching their length to 2.0 cm.

Repeat the stretching procedure for all of the remaining coils 13. At the end the antenna should measure 42.5 cm from the plate to the top.

The finished antenna should be 42.5 cm from the plate to the end of the wire. 14. If you have a spectrum analyzer with a tracking generator and a directional coupler, you can check the curve of the reflected power of the antenna. The picture below shows the display of the spectrum analyzer.

A spectrum plot of the reflected power of the collinear omni.

If you intend to use this antenna outside, you will need to weatherproof it. The simplest method is to enclose the whole thing in a large piece of PVC pipe closed with caps. Cut a hole at the bottom for the transmission line, and seal the antenna shut with silicone or PVC glue.

Cantenna The waveguide antenna, sometimes called a Cantenna, uses a tin can as a waveguide and a short wire soldered on an N connector as a probe for coaxial-cable-to-waveguide transition. It can be easily built at just the price of the connector, recycling a food, juice, or other tin can. It is a directional antenna, useful for short to medium distance point-to-point links. It may be also used as a feeder for a parabolic dish or grid. Not all cans are good for building an antenna because there are dimensional constraints. 1. The acceptable values for the diameter D of the feed are between 0.60 and 0.75 wavelength in air at the design frequency. At 2.44 GHz the wavelength is 12.2 cm, so the can diameter should be in the range of 7.3 - 9.2 cm. 2. The length L of the can preferably should be at least 0.75 G, where G is the guide wavelength and is given by: G = ---------------------------------sqrt(1 ( / 1.706D)2) For D = 7.3 cm, we need a can of at least 56.4 cm, while for D = 9.2 cm we need a can of at least 14.8 cm. Generally the smaller the diameter, the longer the can should be. For our example, we will use oil cans that have a diameter of 8.3 cm and a height of about 21 cm. 3. The probe for coaxial cable to waveguide transition should be positioned at a distance S from the bottom of the can, given by: S = 0,25 G Its length should be 0.25 , which at 2.44 GHz corresponds to 3.05 cm.

Dimensional constraints on the cantenna

The gain for this antenna will be in the order of 10 to 14 dBi, with a beamwidth of around 60 degrees.

The finished cantenna Parts list one screw-on N-type female connector 4 cm of copper or brass wire of 2 mm of diameter an oil can of 8.3 cm of diameter and 21 cm of height

Parts needed for the can antenna.

Tools required Can opener Ruler Pliers File Soldering iron Solder Drill with a set of bits for metal (with a 1.5 cm diameter bit) Vice or clamp Spanner or monkey wrench Hammer Punch

Construction 1. With the can opener, carefully remove the upper part of the can.

Be careful of sharp edges when opening the can. The circular disk has a very sharp edge. Be careful when handling it! Empty the can and wash it with soap. If the can contained pineapple, cookies, or some other tasty treat, have a friend serve the food.

2. With the ruler, measure 6.2 cm from the bottom of the can and draw a point. Be careful to measure from the inner side of the bottom. Use a punch (or a small drill bit or a Phillips screwdriver) and a hammer to mark the point. This makes it easier to precisely drill the hole. Be careful not to change the shape of the can doing this by inserting a small block of wood or other object in the can before tapping it.

Mark the hole before drilling. 3. With a small diameter drill bit, make a hole at the center of the plate. Increase the diameter of the hole using bits with an increasing diameter. The hole should fit exactly the N connector. Use the file to smooth the border of the hole and to remove the painting around it in order to ensure a better electrical contact with the connector.

Carefully drill a pilot hole, then use a larger bit to finish the job. 4. Smooth with the file one end of the wire. Tin the wire for around 0.5 cm at the same end helping yourself with the vice.

Tin the end of the wire before soldering 5. With the soldering iron, tin the central pin of the connector. Keeping the wire vertical with the pliers, solder its tinned side in the hole of the central pin.

Solder the wire to the gold cup on the N connector 6. Insert a washer and gently screw the nut onto the connector. Trim the wire at 3.05 cm measured from the bottom part of the nut.

The length of the wire is critical.

7. Unscrew the nut from the connector, leaving the washer in place. Insert the connector into the hole of the can. Screw the nut on the connector from inside the can.

Assemble the antenna 8. Use the pliers or the monkey wrench to screw firmly the nut on the connector. You are done!

Your finished cantenna. As with the other antenna designs, you should make a weatherproof enclosure for the antenna if you wish to use it outdoors. PVC works well for the can antenna. Insert the entire can in a large PVC tube, and seal the ends with caps and glue. You will need to drill a hole in the side of the tube to accommodate the N connector on the side of the can.

Cantenna as dish feed As with the USB dongle parabolic, you can use the cantenna design as a feeder for significantly higher gain. Mount the can on the parabolic with theopening of the can pointed at the center of the dish. Use the technique described in the USB dongle antenna example (watching signal strength changes over time) to find the optimum location of the can for the dish you are using. By using a well-built cantenna with a properly tuned parabolic, you can achieve an overall antenna gain of 30dBi or more. As the size of the parabolic increases, so does the potential gain and directivity of the antenna. With very large parabolas, you can achieve significantly higher gain. For example, in 2005, a team of college students successfully established a link from Nevada to Utah in the USA. The link crossed a distance of over 200 kilometers! The wireless enthusiasts used a 3.5 meter satellite dish to establish an 802.11b link that ran at 11Mbps, without using an amplifier. Details about this achievement can be found at http://www.wifi-shootout.com/

NEC2 NEC2 stands for Numerical Electromagnetics Code (version 2) and is a free antenna modeling package. NEC2 lets you build an antenna model in 3D, and then analyzes the antennas electromagnetic response. It was developed more than ten years ago and has been compiled to run on many different computer systems. NEC2 is particularly effective for analyzing wiregrid models, but also has some surface patch modeling capability. The antenna design is described in a text file, and then the model is built using this text description. An antenna described in NEC2 is given in two parts: its structure and a sequence of controls. The structure is simply a numerical description of where the different parts of the antenna are located, and how the wires are connected up. The controls tell NEC where the RF source is connected. Once these are defined, the transmitting antenna is then modeled. Because of the reciprocity theorem the transmitting gain pattern is the same as the receiving one, so modeling the transmission characteristics is sufficient to understand the antenna's behavior completely. A frequency or range of frequencies of the RF signal must be specified. The next important element is the character of the ground. The conductivity of the earth varies from place to place, but in many cases it plays a vital role in determining the antenna gain pattern. To run NEC2 on Linux, install the NEC2 package from the URL below. To launch it, type nec2 and enter the input and output filenames. It is also worth installing the xnecview package for structure verification and radiation pattern plotting. If all went well you should have a file containing the output. This can be broken up into various sections, but for a quick idea of what it represents a gain pattern can be plotted using xnecview. You should see the expected pattern, horizontally omnidirectional, with a peak at the optimum angle of takeoff. Windows and Mac versions are also available. The advantage of NEC2 is that we can get an idea of how the antenna worksbefore building it, and how we can modify the design in order to get the maximum gain. It is a complex tool and requires some research to learn how to use it effectively, but it is an invaluable tool for antenna designers. NEC2 is available from http://www.nec2.org/ Online documentation can be obtained from the "Unofficial NEC Home Page" at http://www.nittany-scientific.com/nec .

Networking Hardware
In the last couple of years, an unprecedented surge in interest in wireless networking hardware has brought a huge variety of inexpensive equipment to the market. So much variety, in fact, that it would be impossible to catalog every available component. In this chapter, well look at the sort of features and attributes that are desirable in a wireless component, and see several examples of commercial and DIY gear that has worked well in the past.

Wired wireless With a name like wireless, you may be surprised at how many wires are involved in making a simple point-to-point link. A wireless node consists of many components, which must all be connected to each other with appropriate cabling. You obviously need at least one computer connected to an Ethernet network, and a wireless router or bridge attached to the same network. Radio components need to be connected to antennas, but along the way they may need to interface with an amplifier, lightning arrestor, or other device. Many components require power, either via an AC mains line or using a DC transformer. All of these components use various sorts of connectors, not to mention a wide variety of cable types and thicknesses. Now multiply those cables and connectors by the number of nodes you will bring online, and you may well be wondering why this stuff is referred to as wireless. The diagram on the next page will give you some idea of the cabling required for a typical point-topoint link. Note that this diagram is not to scale, nor is it necessarily the best choice of network design. But it will introduce you to many common interconnects and components that you will likely encounter in the real world.

Component interconnects While the actual components used will vary from node to node, every installation will incorporate these parts: 1. An existing computer or network connected to an Ethernet switch. 2. A device that connects that network to a wireless device (a wireless router, bridge, or repeater). 3. An antenna that is connected via feed line, or is integrated into the wireless device itself. 4. Electrical components consisting of power supplies, conditioners, and lightning arrestors. The actual selection of hardware should be determined by establishing the requirements for the project, determining the available budget, and verifying that the project is feasible using the available resources (including providing for spares and ongoing maintenance costs). As discussed before, establishing the scope of your project is critical before any purchasing decisions are made.

Choosing wireless components Unfortunately, in a world of competitive hardware manufacturers and limited budgets, the price tag is the single factor that usually receives the most attention. The old saying that you get what you pay for often holds true when buying high tech equipment, but should not be considered an absolute truth. While the price tag is an important part of any purchasing decision, it is vital to understand precisely what you get for your money so you can make a choice that fits your needs. When comparing wireless equipment for use in your network, be sure to consider these variables: Interoperability. Will the equipment you are considering work with equipment from other manufacturers? If not, is this an important factor for this segment of your network? If the gear in question supports an open protocol (such as 802.11b/g), then it will likely interoperate with equipment from other sources. Range. As we saw, range is not something inherent in a particular piece of equipment. A devices range depends on the antenna connected to it, the surrounding terrain, the characteristics of the device at the other end of the link, and other factors. Rather than relying on a semi-fictional range rating supplied by the manufacturer, it is more useful to know the transmission power of the radio as well as the antenna gain (if an antenna is included). With this information, you can calculate the theoretical range as described before. Radio sensitivity. How sensitive is the radio device at a given bit rate? The manufacturer should supply this information, at least at the fastest and slowest speeds. This can be used as a measure of the quality of the hardware, as well as allow you to complete a link budget calculation. As we saw before, a lower number is better for radio sensitivity. Throughput. Manufacturers consistently list the highest possible bit rate as the speed of their equipment. Keep in mind that the radio symbol rate (eg. 54Mbps) is never the actual throughput rating of the device (eg. About 22Mbps for 802.11g). If throughput rate information is not available for the device you are evaluating, a good rule of thumb is to divide the device speed by two, and subtract 20% or so. When in doubt, perform throughput testing on an evaluation unit before committing to purchasing a large amount of equipment that has no official throughput rating. Required accessories. To keep the initial price tag low, vendors often leave out accessories that are required for normal use. Does the price tag include all power adapters? (DC supplies are typically included; power over Ethernet injectors typically are not. Double-check input voltages as well, as equipment is often provided with a US-centric power supply). What about pigtails, adapters, cables, antennas, and radio cards? If you intend to use it outdoors, does the device include a weatherproof case? Availability. Will you be able to easily replace failed components? Can you order the part in large quantity, should your project require it? What is the projected life span of this particular product, both in terms of useful running time in-the-field and likely availability from the vendor?

Other factors. Be sure that other needed features are provided for to meet your particular needs. For example, does the device include an external antenna connector? If so, what type is it? Are there user or throughput limits imposed by software, and if so, what is the cost to increase these limits? What is the physical form factor of the device? How much power does it consume? Does it support POE as a power source? Does the device provide encryption, NAT, bandwidth monitoring tools, or other features critical to the intended network design? By answering these questions first, you will be able to make intelligent buying decisions when it comes time to choose networking hardware. It is unlikely that you will be able to answer every possible question before buying gear, but if you prioritize the questions and press the vendor to answer them before committing to a purchase, you will make the best use of your budget and build a network of components that are well suited to your needs.

Commercial vs. DIY solutions Your network project will almost certainly consist of components purchased from vendors as well as parts that are sourced or even fabricated locally. This is a basic economic truth in most areas of the world. At this stage of human technology, global distribution of information is quite trivial compared to global distribution of goods. In many regions, importing every component needed to build a network is prohibitively expensive for all but the largest budgets. You can save considerable money in the short term by finding local sources for parts and labor, and only importing components that must be purchased. Of course, there is a limit to how much work can be done by any individual or group in a given amount of time. To put it another way, by importing technology, you can exchange money for equipment that can solve a particular problem in a comparatively short amount of time. The art of building local telecommunications infrastructure lies in finding the right balance of money to effort needed to be expended to solve the problem at hand. Some components, such as radio cards and antenna feed line, are likely far too complex to consider having them fabricated locally. Other components, such as antennas and towers, are relatively simple and can be made locally for a fraction of the cost of importing. Between these extremes lie the communication devices themselves. By using off-the-shelf radio cards, motherboards, and other components, you can build devices that provide features comparable (or even superior) to most commercial implementations. Combining open hardware platforms with open source software can yield significant bang for the buck by providing custom, robust solutions for very low cost. This is not to say that commercial equipment is inferior to a do-it-yourself solution. By providing so-called turn-key solutions, manufacturers not only save development time, but they can also allow relatively unskilled people to install and maintain equipment. The chief strengths of commercial solutions are that they provide support and a (usually limited) equipment warranty. They also provide a consistent platform that tends to lead to very stable, often interchangeable network installations. If a piece of equipment simply doesnt work or is difficult to configure or troubleshoot, a good manufacturer will assist you. Should the equipment fail in normal use (barring extreme damage, such as a lightning strike) then the manufacturer will typically replace it. Most will provide these services for a limited time as part of the purchase price, and many

offer support and warranty for an extended period for a monthly fee. By providing a consistent platform, it is simple to keep spares on hand and simply swap out equipment that fails in the field, without the need for a technician to configure equipment on-site. Of course, all of this comes at comparatively higher initial cost for the equipment compared to off-the-shelf components. From a network architects point of view, the three greatest hidden risks when choosing commercial solutions are vendor lock-in, discontinued product lines, and ongoing licensing costs. It can be costly to allow the lure of ill-defined new features drive the development of your network. Manufacturers will frequently provide features that are incompatible with their competition by design, and then issue marketing materials to convince you that you simply cannot live without them (regardless of whether the feature contributes to the solution of your communications problem). As you begin to rely on these features, you will likely decide to continue purchasing equipment from the same manufacturer in the future. This is the essence of vendor lock-in. If a large institution uses a significant amount of proprietary equipment, it is unlikely that they will simply abandon it to use a different vendor. Sales teams know this (and indeed, some rely on it) and use vendor lock-in as a strategy for price negotiations. When combined with vendor lock-in, a manufacturer may eventually decide to discontinue a product line, regardless of its popularity. This ensures that customers, already reliant on the manufacturers proprietary features, will purchase the newest (and nearly always more expensive) model. The long term effects of vendor lock-in and discontinued products are difficult to estimate when planning a networking project, but should be kept in mind. Finally, if a particular piece of equipment uses proprietary computer code, you may need to license use of that code on an ongoing basis. The cost of these licenses may vary depending on features provided, number of users, connection speed, or other factors. If the license fee is unpaid, some equipment is designed to simply stop working until a valid, paid-up license is provided! Be sure that you understand the terms of use for any equipment you purchase, including ongoing licensing fees. By using generic equipment that supports open standards and open source software, you can avoid some of these pitfalls. For example, it is very difficult to become lockedin to a vendor that uses open protocols (such as TCP/IP over 802.11a/b/g). If you encounter a problem with the equipment or the vendor, you can always purchase equipment from a different vendor that will interoperate with what you have already purchased. It is for thesereasons that we recommend using proprietary protocols and licensed spectrum only in cases where the open equivalent (such as 802.11a/b/g) is not technically feasible. Likewise, while individual products can always be discontinued at any time, you can limit the impact this will have on your network by using generic components. For example, a particular motherboard may become unavailable on the market, but you may have a number of PC motherboards on hand that will perform effectively the same task. We will see some examples of how to use these generic components to build a complete wireless node later in this guide. Obviously, there should be no ongoing licensing costs involved with open source software (with the exception of a vendor providing extended support or some other service, without charging for the use of the software itself). There have occasionally been vendors who capitalize on the gift that open source programmers have given to the world by offering the code for sale on an

ongoing licensed basis, thereby violating the terms of distribution set forth by the original authors. It would be wise to avoid such vendors, and to be suspicious of claims of free software that come with an ongoing license fee.The disadvantage of using open source software and generic hardware is clearly the question of support. As problems with the network arise, you will need to solve those problems for yourself. This is often accomplished by consulting free online resources and search engines, and applying code patches directly. If you do not have team members who are competent and dedicated to designing a solution to your communications problem, then it can take a considerable amount of time to get a network project off the ground. Of course, there is never a guarantee that simply throwing money at the problem will solve it either. While we provide many examples of how to do much of the work yourself, you may find this work very challenging. You will need to find the balance of commercial solutions and the do-it yourself approach that works for project. In short, always define the scope of your network first, identify the resources you can bring to bear on the problem, and allow the selection of equipment to naturally emerge from the results. Consider commercial solutions as well as open components, while keeping in mind the long-term costs of both. When considering which equipment to use, always remember to compare the expected useful distance, reliability, and throughput, in addition to the price. Be sure to include any ongoing license fees when calculating the overall cost of the equipment. And finally, make sure that the radios you purchase operate in an unlicensed band where you are installing them, or if you must use licensed spectrum, that you have budget and permission to pay for the appropriate licenses.

Professional lightning protection Lightning is a natural predator of wireless equipment. There are two different ways lightning can strike or damage equipment: direct hits or induction hits. Direct hits happen when lightning actually hits the tower or antenna. Induction hits are caused when lightning strikes near the tower. Imagine a negatively charged lightning bolt. Since like charges repel each other, that bolt will cause the electrons in the cables to move away from the strike, creating current on the lines. This can be much more current than the sensitive radio equipment can handle. Either type of strike will usually destroy unprotected equipment.

A tower with a heavy copper grounding wire.

Protecting wireless networks from lightning is not an exact science, and there is no guarantee that a lightning strike will not happen, even if every single precaution is taken. Many of the methods used will help prevent both direct and induction strikes. While it is not necessary to use every single lightning protection method, using more methods will help further protect the equipment. The amount of lightning historically observed within a service area will be the biggest guide to how much needs to be done. Start at the very bottom of the tower. Remember, the bottom of the tower is below the ground. After the tower foundation is laid, but before the hole is backfilled, a ring of heavy braided ground wire should have been installed with the lead extending above ground surfacing near a tower leg. The wire should be American Wire Gauge (AWG) #4 or thicker. In addition, a backup ground or earthing rod should be driven into the ground, and a ground wire run from the rod to the lead from the buried ring. It is important to note that not all steel conducts electricity the same way. Some types of steel act as better electrical conductors then others, and different surface coatings can also affect how tower steel handles electrical current. Stainless steel is one of the worst conductors, and rust proof coatings like galvanizing or paint lessen the conductivity of the steel. For this reason, a braided ground wire is run from the bottom of the tower all the way to the top. The bottom needs to be properly attached to the leads from both the ring and the backup ground rod. The top of the tower should have a lightning rod attached, and the top of that needs to be pointed. The finer and sharper the point, the more effective the rod will be. The braided ground wire from the bottom needs to be terminated at this grounding rod. It is very important to be sure that the ground wire is connected to the actual metal. Any sort of coating, such as paint, must be removed before the wire is attached. Once the connection is made, the exposed area can be repainted, covering the wire and connectors if necessary to save the tower from rust and other corrosion. The above solution details the installation of the basic grounding system. It provides protection for the tower itself from direct hits, and installs the base system to which everything else will connect. The ideal protection for indirect induction lightning strikes are gas tube arrestors at both ends of the cable. These arrestors need to be grounded directly to the ground wire installed on the tower if it is at the high end. The bottom end needs to be grounded to something electrically safe, like a ground plate or a copper pipe that is consistently full of water. It is important to make sure that the outdoor lightning arrestor is weatherproofed. Many arresters for coax cables are weatherproofed, while many arresters for CAT5 cable are not. In the event that gas arrestors are not being used, and the cabling is coax based, then attaching one end of a wire to the shield of the cable and the other to the ground wire installed on the towers will provide some protection. This can provide a path for induction currents, and if the charge is weak enough, it will not affect the conductor wire of the cable. While this method is by no means as good of protection as using the gas arrestors, it is better then doing nothing at all.

Building an access point from a PC Unlike consumer operating systems (such as Microsoft Windows), the GNU/ Linux operating system gives a network administrator the potential for full access to the networking stack. One can access and manipulate network packets at any level from the data-link layer through the application layer. Routing decisions can be made based on any information contained in a network packet, from the routing addresses and ports to the contents of the data segment. A Linux-based access point can act as a router, bridge, firewall, VPN concentrator, application server, network monitor, or virtually any other networking role you can think of. It is freely available software, and requires no licensing fees. GNU/Linux is a very powerful tool that can fill a broad variety of roles in a network infrastructure. Adding a wireless card and Ethernet device to a PC running Linux will give you a very flexible tool that can help you deliver bandwidth and manage your network for very little cost. The hardware could be anything from a recycled laptop or desktop machine to an embedded computer, such as a Linksys WRT54G or Metrix networking kit. In this section we will see how to configure Linux in the following configurations: As a wireless access point with Masquerading/NAT and a wired connection to the Internet (also referred to as a wireless gateway). As a wireless access point that acts as a transparent bridge. The bridge can be used either as a simple access point, or as a repeater with 2 radios. Consider these recipes as a starting point. By building on these simple examples, you can create a server that fits precisely into your network infrastructure.

Prerequisites Before proceeding, you should already be familiar with Linux from a users perspective, and be capable of installing the Gnu/Linux distribution of your choice. A basic understanding of the command line interface (terminal) in Linux is also required. You will need a computer with one or more wireless cards already installed, as well as a standard Ethernet interface. These examples use a specific card and driver, but there are a number of different cards that should work equally well. Wireless cards based on the Atheros and Prism chipsets work particularly well. These examples are based on Ubuntu Linux version 5.10 (Breezy Badger), with a wireless card that is supported by the HostAP or MADWiFi drivers. For more information about these drivers, see http://hostap.epitest.fi/ and http://madwifi.org/ . The following software is required to complete these installations. It should be provided in your Linux distribution: Wireless Tools (iwconfig, iwlist commands) iptables firewall dnsmasq (caching DNS server and DHCP server)

The CPU power required depends on how much work needs to be done beyond simple routing and NAT. For many applications, a 133MHz 486 is perfectly capable of routing packets at wireless speeds. If you intend to use a lot of encryption (such as WEP or a VPN server), then you will need something faster. If you also want to run a caching server (such as Squid) then you will need a computer with plenty of fast disk space and RAM. A typical router that is only performing NAT will operate will with as little as 64MB of RAM and storage. When building a machine that is intended to be part of your network infrastructure, keep in mind that hard drives have a limited lifespan compared to most other components. You can often use solid state storage, such as a flash disk, in place of a hard drive. This could be a USB flash drive (assuming your PC will boot from USB), or a Compact Flash card using a CF to IDE adapter. These adapters are quite inexpensive, and will make a CF card appear act like standard IDE hard drive. They can be used in any PC that supports IDE hard drives. Since they have no moving parts, they will operate for many years through a much wider range of temperatures than a hard disk will tolerate. Scenario 1: Masquerading access point This is the simplest of the scenarios, and is especially useful in situations where you want a single access point for an office setting. This is easiest in a situation where: 1. There is an existing dedicated firewall and gateway running Linux, and you just want to add a wireless interface. 2. You have an old refurbished computer or laptop available, and prefer to use that as an access point. 3. You require more power in terms of monitoring, logging and/or security than most commercial access points provide, but don't want to splurge on an enterprise access point. 4. You would like a single machine to act as 2 access points (and firewall) so that you can offer both a secure network access to the intranet, as well as open access to guests.

Initial setup Start up with an already configured computer running GNU/Linux. This could be an Ubuntu Server installation, or Fedora Core. The computer must have at least 2 interfaces for this to work, and at least one of these interfaces should be wireless. The rest of this description assumes that your cabled Ethernet port (eth0) is connected to the Internet, and that there is a wireless interface (wlan0) that will provide the access point functionality. To find out if your chipset supports master mode, try the following command as root: # iwconfig wlan0 mode Master ...replacing wlan0 with the name of your interface. If you get an error message, then your wireless card doesnt support access point mode. You can still try the same setup in Ad-hoc

mode, which is supported by all chipsets. This requires that you to set all the laptops that are connecting to this access point into Ad-hoc mode as well, and may not work quite the way you are expecting. It is usually better to find a wireless card that will support AP mode. See the HostAP and MADWiFi websites mentioned earlier for a list of supported cards. Before continuing, make sure dnsmasq is installed on your machine. You can use the graphical package manager of your distribution to install it. In Ubuntu you can simply run the following as root: # apt-get install dnsmasq

Setting up the interfaces Set up your server so that eth0 is connected to the Internet. Use the graphical configuration tool that came with your distribution. If your Ethernet network uses DHCP, you could try the following command as root: # dhclient eth0 You should receive an IP address and default gateway. Next, set your wireless interface to Master mode and give it a name of your choice: # iwconfig wlan0 essid my network mode Master enc off The enc off switch turns off WEP encryption. To enable WEP, add a hexkey string of the correct length: # iwconfig wlan0 essid my network mode Master enc 1A2B3C4D5E Alternately, you can use a readable string by starting with s: # iwconfig wlan0 essid my network mode Master enc s:apple Now give your wireless interface an IP address in a private subnet, but make sure it is not the same subnet as that of your Ethernet adapter: # ifconfig wlan0 10.0.0.1 netmask 255.255.255.0 broadcast 10.0.0.255 up Setting up masquerading in the kernel In order for us to be able to translate addresses between the two interfaces on the computer, we need to enable masquerading (NAT) in the linux kernel. First we load the relevant kernel module: # modprobe ipt_MASQUERADE Now we will flush all existing firewall rules to ensure that the firewall is not blocking us from forwarding packets between the two interfaces. If you have an existing firewall running, make sure you know how to restore the existing rules later before proceeding. # iptables F

Enable the NAT functionality between the two interfaces # iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE Finally we need to enable the kernel to forward packets between interfaces: # echo 1 > /proc/sys/net/ipv4/ip_forward On Debian-based Linux distributions such as Ubuntu, this change can also be made by editing the file /etc/network/options, and be sure that ip_forward is set to yes: ip_forward=yes and then restarting the network interfaces with: # /etc/init.d/network restart or # /etc/init.d/networking restart

Setting up the DHCP server At this point we actually should have a working access point. It can be tested by connecting to the wireless network my network with a separate machine and giving that machine an address in the same address range as our wireless interface on the server (10.0.0.0/24 if you followed the examples). If you have enabled WEP, be sure to use the same key that you specified on the AP. In order to make it easier for people to connect to the server without knowing the IP address range, we will set up a DHCP server to automatically hand outaddresses to wireless clients. We use the program dnsmasq for this purpose. As the name indicates, it provides a caching DNS server as well as a DHCP server. This program was developed especially for use with firewalls performing NAT. Having a caching DNS server is especially helpful if your Internet connection is a high-latency and/or lowbandwidth connection, such as a VSAT or dial-up. It means that many DNS queries can be resolved locally, saving a lot of traffic on the Internet connection, and also making the connection feel noticeably faster for those connecting. Install dnsmasq with your distributions package manager. If dnsmasq is not available as a package, download the source code and install it manually. It is available from http://www.thekelleys.org.uk/dnsmasq/doc.html. All that is required for us to run dnsmasq is to edit a few lines of the dnsmasq configuration file, /etc/dnsmasq.conf.

The configuration file is well commented, and has many options for various types of configuration. To get the basic DHCP server up and running we just need to uncomment and/or edit two lines. Find the lines that starts: interface= ...and make sure it reads: interface=wlan0 ...changing wlan0 to match name of your wireless interface. Then find the line that starts with: #dhcp-range= Uncomment the line and edit it to suit the match addresses being used, i.e. dhcp-range=10.0.0.10,10.0.0.110,255.255.255.0,6h Then save the file and start dnsmasq: # /etc/init.d/dnsmasq start That's it, you should now be able to connect to the server as an access point, and get an IP address using DHCP. This should let you connect to the Internet through the server.

Adding extra security: Setting up a Firewall Once this is set up and tested, you can add extra firewall rules using whatever firewall tool is included in your distribution. Some typical front-ends for setting up firewall rules include: firestarter - a graphical client for Gnome, which requires that your server is running Gnome knetfilter a graphical client for KDE, which requires that your server is running KDE Shorewall a set of scripts and configuration files that will make it easier to setup an iptables firewall. There are also frontends for shorewall, such as webmin-shorewall fwbuilder - a powerful, but slightly complex graphical tool that will let you create iptables scripts on a machine separate from your server, and then transfer them to the server later. This does not require you to be running a graphical desktop on the server, and is a strong option for the security conscious. Once everything is configured properly, make sure that all settings are reflected in the system startup scripts. This way, your changes will continue to work should the machine need to be rebooted.

Scenario 2: Transparent Bridging access point This scenario can either be used for a two-radio repeater, or for an access point connected to an Ethernet. We use a bridge instead of routing when we want both interfaces on the access point to share the same subnet. This can be particularly useful in networks with multiple access points where we prefer to have a single, central firewall and perhaps authentication server. Because all clients share the same subnet they, can easily be managed with a single DHCP server and firewall without the need for DHCP relay. For example, you could setup a server as the first scenario, but use two wired Ethernet interfaces instead of one wired and one wireless. One inter face would be your Internet connection, and the other would connect to a switch. Then connect as many access points as you require to the same switch, set them up as transparent bridges, and everyone will pass through the same firewall and use the same DHCP server. The simplicity of bridging comes at a cost of efficiency. Since all clients share the same subnet, broadcast traffic will be repeated throughout the network. This is usually fine for small networks, but as the number of clients increases, more wireless bandwidth will be wasted on broadcast network traffic.

Initial setup The initial setup for a bridging access point is similar to that of a masquerading access point, without the requirement of dnsmasq. Follow the initial setup instructions from the previous example. In addition, the bridge-utils package is required for bridging. This package exists for Ubuntu and other Debian-based distributions, as well as for Fedora Core. Make sure it is installed and that the command brctl is available before proceeding.

Setting up the Interfaces On Ubuntu or Debian the network interfaces are configured by editing the file /etc/network/interfaces. Add a section like the following, but change the names of interfaces and the IP addresses accordingly. The IP address and netmask must match that of your existing network. This example assumes you are building a wireless repeater with two wireless interfaces, wlan0 and wlan1. The wlan0 interface will be a client to the office network, and wlan1 will create a network called repeater. Add the following to /etc/network/interfaces:

auto br0 iface br0 inet static address 192.168.1.2 network 192.168.1.0 netmask 255.255.255.0 broadcast 192.168.1.255 gateway 192.168.1.1 pre-up ifconfig wlan 0 0.0.0.0 up pre-up ifconfig wlan1 0.0.0.0 up pre-up iwconfig wlan0 essid office mode Managed pre-up iwconfig wlan1 essid repeater mode Master bridge_ports wlan0 wlan1 post-down ifconfig wlan1 down post-down ifconfig wlan0 down Comment out any other sections in the file that refer to wlan0 or wlan1 to make sure that they don't interfere with our setup. This syntax for setting up bridges via the interfaces file is specific to Debian-based distributions, and the details of actually setting up the bridge are handled by a couple of scripts: /etc/network/if-pre-up.d/bridge And /etc/network/if-post-down.d/bridge. The documentation for these scripts is found in /usr/share/doc/bridge-utils/. If those scripts don't exist on your distribution (such as Fedora Core), here is an alternative setup for /etc/network/interfaces which will achieve the same thing with only marginally more hassle: iface br0 inet static pre-up ifconfig wlan 0 0.0.0.0 up pre-up ifconfig wlan1 0.0.0.0 up pre-up iwconfig wlan0 essid office mode Managed pre-up iwconfig wlan1 essid repeater mode Master pre-up brctl addbr br0 pre-up brctl addif br0 wlan0 pre-up brctl addif br0 wlan1 post-down ifconfig wlan1 down post-down ifconfig wlan0 down post-down brctl delif br0 wlan0 post-down brctl delif br0 wlan1 post-down brctl delbr br0

Starting the bridge Once the bridge is defined as an interface, starting the bridge is as simple as typing: # ifup -v br0 The -v means verbose output and will give you information to what is going on. On Fedora Core (i.e. non-debian distributions) you still need to give your bridge interface an ip address and add a default route to the rest of the network: #ifconfig br0 192.168.1.2 netmask 255.255.255.0 broadcast 192.168.1.255 #route add default gw 192.168.1.1 You should now be able to connect a wireless laptop to this new access point, and connect to the Internet (or at least to the rest of your network) through this box. Use the brctl command to see what your bridge is doing: # brctl show br0

Scenario 1 & 2 the easy way Instead of setting up your computer as an access point from scratch, you may wish to use a dedicated Linux distribution that is specially tailored for this purpose. These distributions can make the job as simple as booting from a particular CD on a computer with a wireless interface. See the section, Wireless-friendly operating systems for more information. As you can see, it is straightforward to provide access point services from a standard Linux router. Using Linux gives you significantly more control over how packets are routed through your network, and allows for features that simply arent possible on consumer grade access point hardware. For example, you could start with either of the above two examples and implement a private wireless network where users are authenticated using a standard web browser. Using a captive portal such as Chillispot, wireless users can be checked against credentials in an existing database (say, a Windows domain server accessible via RADIUS). This arrangement could allow for preferential access to users in the database, while providing a very limited level of access for the general public. Another popular application is the prepaid commercial model. In this model, users must purchase a ticket before accessing the network. This ticket provides a password that is valid for a limited amount of time (typically one day). When the ticket expires, the user must purchase another. This ticketing feature is only available on relatively expensive commercial networking equipment, but can be implemented using free software such as Chillispot and phpMyPrePaid.

Wireless-friendly operating systems There are number of open source operating system that provide useful tools for working with wireless networks. These are intended to be used on repurposed PCs or other networking hardware (rather than on a laptop or server) and are fine-tuned for building wireless networks. Some of these projects include: Freifunk. Based on the OpenWRT project (http://openwrt.org/), the Freifunk firmware brings easy OLSR support to MIPS-based consumer access points, such as the Linksys WRT54G / WRT54GS / WAP54G, Siemens SE505, and others. By simply flashing one of these APs with the Freifunk firmware, you can rapidly build a self-forming OLSR mesh. Freifunk is not currently available for x86 architecture machines. It is maintained by Sven Ola of the Freifunk wireless group in Berlin. You can download the firmware from http://www.freifunk.net/wiki/FreifunkFirmware . Pyramid Linux. Pyramid is a Linux distribution for use on embedded platforms that evolved out of the venerable Pebble Linux platform. It supports several different wireless cards, and has a simple web interface for configuring networking interfaces, port forwarding, WifiDog, and OLSR. Pyramid is distributed and maintained by Metrix Communication LLC, and is available at http://pyramid.metrix.net/. m0n0wall. Based on FreeBSD, m0n0wall is a very tiny but complete firewall package that provides AP services. It is configured from a web interface and the entire system configuration is stored in a single XML file. Its tiny size (less than 6MB) makes it attractive for use in very small embedded systems. Its goal is to provide a secure firewall, and as such does not include userspace tools (it is not even possible to log into the machine over the network). Despite this limitation, it is a popular choice for wireless networkers, particularly those with a background in FreeBSD. You can download m0n0wall from http://www.m0n0.ch/ All of these distributions are designed to fit in machines with limited storage. If you are using a very large flash disk or hard drive, you can certainly install a more complete OS (such as Ubuntu or Debian) and use the machine as a router or access point. It will likely take a fair amount of development time to be sure all needed tools are included, without installing unnecessary packages. By using one of these projects as a starting point for building a wireless node, you will save yourself considerable time and effort.

The Linksys WRT54G One of the most popular consumer access points currently on the market is the Linksys WRT54G. This access point features two external RP-TNC antenna connectors, a four port Ethernet switch, and an 802.11b/g radio. It is configured through a simple web interface. While it is not designed as an outdoor solution, it can be installed in a large sprinkler box or plastic tub for relatively little cost. As of this writing, the WRT54G sells for about $60. Back in 2003, network hackers realized that the firmware that shipped with the WRT54G was actually a version of Linux. This led to a tremendous interest in building custom firmware that extended the capabilities of the router significantly. Some of these new features include client radio mode support, captive portals, and mesh networking. Some popular alternative firmware packages for the WRT54G are: DD-Wrt (http://www.dd-wrt.com), OpenWRT(http://openwrt.org ), Tomato (http://www.polarcloud.com/tomato) Freifunk(http://www.freifunk.net). Unfortunately, in the fall of 2005, Linksys released version 5 of the WRT54G. This hardware revision eliminated some RAM and flash storage on the motherboard, making it very difficult to run Linux (it ships with VxWorks, a much smaller operating system that does not allow easy customization). Linksys also released the WRT54GL, which is essentially the WRT54G v4 (which runs Linux) with a slightly bigger price tag. A number of other Linksys access points also run Linux, including the WRT54GS and WAP54G. While these also have relatively low price tags, the hardware specifications may change at any time. It is difficult to know which hardware revision is used without opening the packaging, making it risky to purchase them at a retail store and practically impossible to order online. While the WRT54GL is guaranteed to run Linux, Linksys has made it known that it does not expect to sell this model in large volume, and it is unclear how long it will be offered for sale. Fortunately, wireless hackers have now been able to install custom firmware on the notoriously difficult WRT54G version 5 and 6, and the latest revisions as well (v7 and v8). For details on getting alternate firmware installed on a v5 or v6 access point see: http://www.scorpiontek.org/portal/content/view/27/36 For more information about the current state of Linksys wireless router hacking, see http://linksysinfo.org Note: more information about installing and using OpenWRT is discussed later.

DD-WRT One popular alternate firmware for the Linksys family of access point hardware is DD-WRT (http://www.dd-wrt.com/). It includes several useful features, including radio client mode, adjustable transmission power, various captive portals, QoS support, and much more. It uses an intuitive web-based configuration tool (unencrypted or via HTTPS), and also provides SSH and telnet access. Several versions of the firmware are available from the DD-WRT website. The general procedure for upgrading is to download the version of the firmware appropriate for your hardware, and upload it via the router's "firmware update" feature. Specific installation details vary according to the hardware version of your router. In addition to Linksys hardware, DDWRT will run on Buffalo, ASUS, the La Fonera, and other access points. For specific instructions for your hardware, see the installation guide on the DD-WRT wiki at http://www.ddwrt.com/wiki/index.php/Installation. The default login for a fresh DD-WRT installation is root with the password admin.

The DD-WRT (v23) control panel

Security & Monitoring


In a traditional wired network, access control is very straightforward: If a person has physical access to a computer or network hub, they can use (or abuse) the network resources. While software mechanisms are an important component of network security, limiting physical access to the network devices is the ultimate access control mechanism. Simply put, if all terminals and network components are only accessible to trusted individuals, the network can likely be trusted. The rules change significantly with wireless networks. While the apparent range of your access point may seem to be just a few hundred meters, a user with a high gain antenna may be able to make use of the network from several blocks away. Should an unauthorized user be detected, is impossible to simply trace the cable back to the users location. Without transmitting a single packet, a nefarious user can even log all network data to disk. This data can later be used to launch a more sophisticated attack against the network. Never assume that radio waves simply stop at the edge of your property line. It is usually unreasonable to completely trust all users of the network, even on wired networks. Disgruntled employees, uneducated network users, and simple mistakes on the part of honest users can cause significant harm to network operations. As the network architect, your goal is to facilitate private communication between legitimate users of the network. While a certain amount of access control and authentication is necessary in any network, you have failed in your job if legitimate users find it difficult to use the network to communicate. Theres an old saying that the only way to completely secure a computer is to unplug it, lock it in a safe, destroy the key, and bury the whole thing in con crete. While such a system might be completely secure, it is useless for communication. When you make security decisions for your network, remember that above all else, the network exists so that its users can communicate with each other. Security considerations are important, but should not get in the way of the networks users.

Physical security When installing a network, you are building an infrastructure that people depend on. Security measures exist to ensure that the network is reliable. For many installations, outages often occur due to human tampering, whether accidental or not. Networks have physical components, such as wires and boxes, which are easily disturbed. In many installations, people will not understand the purpose of the installed equipment, or curiosity may lead them to experiment. They may not realize the importance of a cable connected to a port. Someone may unplug an Ethernet cable so that they can connect their laptop for 5 minutes, or move a switch because it is in their way. A plug might be removed from a power bar because someone needs that receptacle.

Assuring the physical security of an installation is paramount. Signs and labels will only be useful to those who can read your language. Putting things out of the way and limiting access is the best means to assure that accidents and tinkering do not occur. In less developed economies, proper fasteners, ties, or boxes will not be as easy to find. You should be able to find electrical supplies that will work just as well. Custom enclosures are also easy to manufacture and should be considered essential to any installation. It is often economical to pay a mason to make holes and install conduit. Where this would be an expensive option in the developed world, this type of labour intensive activity can be affordable in Southern countries. PVC can be embedded in cement walls for passing cable from room to room. This avoids the need to smash new holes every time a cable needs to be passed. Plastic bags can be stuffed into the conduit around the cables for insulation. Small equipment should be mounted on the wall and larger equipment should be put in a closet or in a cabinet.

Switches Switches, hubs or interior access points can be screwed directly onto a wall with a wall plug. It is best to put this equipment as high as possible to reduce the chance that someone will touch the device or its cables.

Cables At the very least, cables should be hidden and fastened. It is possible to find plastic cable conduit that can be used in buildings. If you cannot find it, simple cable attachments can be nailed into the wall to secure the cable. This will make sure that the cable doesn't hang where it can be snagged, pinched or cut. It is preferable to bury cables, rather than to leave them hanging across a yard. Hanging wires might be used for drying clothes, or be snagged by a ladder, etc. To avoid vermin and insects, use plastic electrical conduit. The marginal expense will be well worth the trouble. The conduit should be buried about 30 cm deep, or below the frost level in cold climates. It is worth the extra investment of buying larger conduit than is presently required, so that future cables can be run through the same tubing. Consider labeling buried cable with a "call before you dig" sign to avoid future accidental outages.

Power It is best to have power bars locked in a cabinet. If that is not possible, mount the power bar under a desk, or on the wall and use duct tape (or gaffer tape, a strong adhesive tape) to secure the plug into the receptacle. On the UPS and power bar, do not leave any empty receptacles. Tape them if necessary. People will have the tendency to use the easiest receptacle, so make

these critical ones difficult to use. If you do not, you might find a fan or light plugged into your UPS; though it is nice to have light, it is nicer to keep your server running!

Water Protect your equipment from water and moisture. In all cases make sure that your equipment, including your UPS is at least 30 cm from the ground, to avoid damage from flooding. Also try to have a roof over your equipment, so that water and moisture will not fall onto it. In moist climates, it is important that the equipment has proper ventilation to assure that moisture can be exhausted. Small closets need to have ventilation, or moisture and heat can degrade or destroy your gear.

Masts Equipment installed on a mast is often safe from thieves. Nevertheless, to deter thieves and to keep your equipment safe from winds it is good to overengineer mounts. Painting equipment a dull white or grey color reflects the sun and makes it look plain and uninteresting. Panel antennas are often preferred because they are much more subtle and less interesting than dishes. Any installation on walls should be high enough to require a ladder to reach. Try choosing well-lit but not prominent places to put equipment. Also avoid antenna that resemble television antennae, as those are items that will attract interest by thieves, where a wifi antenna will be useless to the average thief.

Threats to the network One critical difference between Ethernet and wireless is that wireless networks are built on a shared medium. They more closely resemble the old network hubs than modern switches, in that every computer connected to the network can see the traffic of every other user. To monitor all network traffic on an access point, one can simply tune to the channel being used, put the network card into monitor mode, and log every frame. This data might be directly valuable to an eavesdropper (including data such as email, voice data, or online chat logs). It may also provide passwords and other sensitive data, making it possible to compromise the network even further. As well see later in this chapter, this problem can be mitigated by the use of encryption. Another serious problem with wireless networks is that its users are relatively anonymous. While it is true that every wireless device includes a unique MAC address that is supplied by the manufacturer, these addresses can often be changed with software. Even when the MAC address is known, it can be very difficult to judge where a wireless user is physically located. Multipath effects, high-gain antennas, and widely varying radio transmitter characteristics can make it impossible to determine if a malicious wireless user is sitting in the next room or is in an apartment building a mile away.

While unlicensed spectrum provides a huge cost savings to the user, it has the unfortunate side effect that denial of service (DoS) attacks are trivially simple. By simply turning on a high powered access point, cordless phone, video transmitter, or other 2.4GHz device, a malicious person could cause significant problems on the network. Many network devices are vulnerable to other forms of denial of service attacks as well, such as disassociation flooding and ARP table overflows. Here are several categories of individuals who may cause problems on a wireless network: Unintentional users. As more wireless networks are installed in densely populated areas, it is common for laptop users to accidentally associate to the wrong network. Most wireless clients will simply choose any available wireless network when their preferred network is unavailable. The user may then make use of this network as usual, completely unaware that they may be transmitting sensitive data on someone elses network. Malicious people may even take advantage of this by setting up access points in strategic locations, to try to attract unwitting users and capture their data. The first step in avoiding this problem is educating your users, and stressing the importance of connecting only to known and trusted networks. Many wireless clients can be configured to only connect to trusted networks, or to ask permission before joining a new network. As we will see later, users can safely connect to open public networks by using strong encryption. War drivers. The war driving phenomenon draws its name from the popular 1983 hacker film, War Games. War drivers are interested in finding the physical location of wireless networks. They typically drive around with a laptop, GPS, and omnidirectional antenna, logging the name and location of any networks they find. These logs are then combined with logs from other war drivers, and are turned into graphical maps depicting the wireless footprint of a particular city. The vast majority of war drivers likely pose no direct threat to networks, but the data they collect might be of interest to a network cracker. For example, it might be obvious that an unprotected access point detected by a war driver is located inside a sensitive building, such as a government or corporate office. A malicious person could use this information to illegally access the network there. Arguably, such an AP should never have been set up in the first place, but war driving makes the problem all the more urgent. As we will see later in this chapter, war drivers who use the popular program NetStumbler can be detected with programs such as Kismet. For more information about war driving, see sites such as http://www.wifimaps.com/, http://www.nodedb.com/, or http://www.netstumbler.com/ . Rogue access points. There are two general classes of rogue access points: those incorrectly installed by legitimate users, and those installed by malicious people who intend to collect data or do harm to the network. In the simplest case, a legitimate network user may want better wireless coverage in their office, or they might find security restrictions on the corporate wireless network too difficult to comply

with. By installing an inexpensive consumer access point without permission, the user opens the entire network up to potential attacks from the inside. While it is possible to scan for unauthorized access points on your wired network, setting a clear policy that prohibits them is very important. The second class of rogue access point can be very difficult to deal with. By installing a high powered AP that uses the same ESSID as an existing network, a malicious person can trick people into using their equipment, and log or even manipulate all data that passes through it. Again, if your users are trained to use strong encryption, this problem is significantly reduced. Eavesdroppers. As mentioned earlier, eavesdropping is a very difficult problem to deal with on wireless networks. By using a passive monitoring tool (such as Kismet), an eavesdropper can log all network data from a great distance away, without ever making their presence known. Poorly encrypted data can simply be logged and cracked later, while unencrypted data can be easily read in real time. If you have difficulty convincing others of this problem, you might want to demonstrate tools such as Etherpeg: (http://www.etherpeg.org/) or Driftnet (http://www.ex-parrot.com/~chris/driftnet/). These tools watch a wireless network for graphical data, such as GIF and JPEG files. While other users are browsing the Internet, these tools simply display all graphics found in a graphical collage. I often use tools such as this as a demonstration when lecturing on wireless security. While you can tell a user that their email is vulnerable without encryption, nothing drives the message home like showing them the pictures they are looking at in their web browser. Again, while it cannot be completely prevented, proper application of strong encryption will discourage eavesdropping. This introduction is intended to give you an idea of the problems you are up against when designing a wireless network. Later in this chapter, we will look at tools and techniques that will help you to mitigate these problems.

Authentication Before being granted access to network resources, users should first be authenticated. In an ideal world, every wireless user would have an identifier that is unique, unchangeable, and cannot be impersonated by other users. This turns out to be a very difficult problem to solve in the real world. The closest feature we have to a unique identifier is the MAC address. This is the 48-bit number assigned by the manufacturer to every wireless and Ethernet device. By employing mac filtering on our access points, we can authenticate users based on their MAC address. With this feature, the access point keeps an internal table of approved MAC addresses. When a wireless user tries to associate to the access point, the MAC address of the client must be on the approved list, or the association will be denied. Alternately, the AP may keep a table of known bad MAC addresses, and permit all devices that are not on the list.

Unfortunately, this is not an ideal security mechanism. Maintaining MAC tables on every device can be cumbersome, requiring all client devices to have their MAC addresses recorded and uploaded to the APs. Even worse, MAC addresses can often be changed in software. By observing MAC addresses in use on a wireless network, a determined attacker can spoof (impersonate) an approved MAC address and successfully associate to the AP. While MAC filtering will prevent unintentional users and even most curious individuals from accessing the network, MAC filtering alone cannot prevent attacks from determined attackers. MAC filters are useful for temporarily limiting access from misbehaving clients. For example, if a laptop has a virus that sends large amounts of spam or other traffic, its MAC address can be added to the filter table to stop the traffic immediately. This will buy you time to track down the user and fix the problem. Another popular authentication feature of wireless the so-called closed network. In a typical network, APs will broadcast their ESSID many times per second, allowing wireless clients (as well as tools such as NetStumbler) to find the network and display its presence to the user. In a closed network, the AP does not beacon the ESSID, and users must know the full name of the network before the AP will allow association. This prevents casual users from discovering the network and selecting it in their wireless client. There are a number of drawbacks to this feature. Forcing users to type in the full ESSID before connecting to the network is error prone and often leads to support calls and complaints. Since the network isnt obviously present in site survey tools like NetStumbler, this can prevent your networks from showing up on war driving maps. But it also means that other network builders cannot easily find your network either, and specifically wont know that you are already using a given channel. A conscientious neighbor may perform a site survey, see no nearby networks, and install their own network on the same channel you are using. This will cause interference problems for both you and your neighbor. Finally, using closed networks ultimately adds little to your overall networks security. By using passive monitoring tools (such as Kismet), a skilled user can detect frames sent from your legitimate clients to the AP. These frames necessarily contain the network name. A malicious user can then use this name to associate to the access point, just like a normal user would. Encryption is probably the best tool we have for authenticating wireless users. Through strong encryption, we can uniquely identify a user in a manner that is very difficult to spoof, and use that identity to determine further network access. Encryption also has the benefit of adding a layer of privacy by preventing eavesdroppers from easily watching network traffic. The most widely employed encryption method on wireless networks is WEP encryption. WEP stands for wired equivalent privacy, and is supported by virtually all 802.11a/b/g equipment. WEP uses a shared 40-bit key to encrypt data between the access point and client. The key must be entered on the APs as well as on each of the clients. With WEP enabled, wireless clients cannot associate with the AP until they use the correct key. An eavesdropper listening to a WEPenabled network will still see traffic and MAC addresses, but the data payload of each packet is encrypted. This provides a fairly good authentication mechanism while also adding a bit of privacy to the network.

WEP is definitely not the strongest encryption solution available. For one thing, the WEP key is shared between all users. If the key is compromised (say, if one user tells a friend what the password is, or if an employee is let go) then changing the password can be prohibitively difficult, since all APs and client devices need to be changed. This also means that legitimate users of the network can still eavesdrop on each others traffic, since they all know the shared key. The key itself is often poorly chosen, making offline cracking attempts feasible. Even worse, the implementation of WEP itself is broken in many access points, making it even easier to crack some networks. While manufacturers have implemented a number of extensions to WEP (such as longer keys and fast rotation schemes), these extensions are not part of the standard, and generally will not interoperate between equipment from different manufacturers. By upgrading to the most recent firmware for all of your wireless devices, you can prevent some of the early attacks found in WEP. WEP can still be a useful authentication tool. Assuming your users can be trusted not to give away the password, you can be fairly sure that your wireless clients are legitimate. While WEP cracking is possible, it is beyond the skill of most users. WEP is quite useful for securing long distance point-topoint links, even on generally open networks. By using WEP on such a link, you will discourage others from associating to the link, and they will likely use other available APs instead. Think of WEP as a handy keep out sign for your network. Anyone who detects the network will see that a key is required, making it clear that they are not welcome to use it. WEPs greatest strength is its interoperability. In order to comply with the 802.11 standards, all wireless devices support basic WEP. While it isnt the strongest method available, it is certainly the most commonly implemented encryption feature. We will look at other more advanced encryption techniques later. For more details about the state of WEP encryption, see these papers: http://www.isaac.cs.berkeley.edu/isaac/wep-faq.html http://www.cs.umd.edu/~waa/wireless.pdf http://www.crypto.com/papers/others/rc4_ksaproc.ps Another data-link layer authentication protocol is Wi-Fi Protected Access, or WPA. WPA was created specifically to deal with the known problems with WEP mentioned earlier. It provides a significantly stronger encryption scheme, and can use a shared private key, unique keys assigned to each user or even SSL certificates to authenticate both the client and the access point. Authentication credentials are checked using the 802.1X protocol, which can consult a third party database such as RADIUS. Through the use of Temporal Key Integrity Protocol (TKIP), keys can be rotated quickly over time, further reducing the likelihood that a particular session can be cracked. Overall, WPA provides significantly better authentication and privacy than standard WEP. WPA requires fairly recent access point hardware and up-to-date firmware on all wireless clients, as well as a substantial amount of configuration. If you are installing a network in a setting where

you control the entire hardware platform, WPA can be ideal. By authenticating both clients and APs, it solves the rogue access point problem and provides many significant advantages over WEP. But in most network settings where the vintage of hardware is mixed and the knowledge of wireless users is limited, WPA can be a nightmare to install. It is for this reason that most sites continue to use WEP, if encryption is used at all.

Captive portals One common authentication tool used on wireless networks is the captive portal. A captive portal uses a standard web browser to give a wireless user the opportunity to present login credentials. It can also be used to present information (such as an Acceptable Use Policy) to the user before granting further access. By using a web browser instead of a custom program for authentication, captive portals work with virtually all laptops and operating systems. Captive portals are typically used on open networks with no other authentication methods (such as WEP or MAC filters). To begin, a wireless user opens their laptop and selects the network. Their computer requests a DHCP lease, which is granted. They then use their web browser to go to any site on the Internet.

The user requests a web page and is redirected

Instead of receiving the requested page, the user is presented with a login screen. This page can require the user to enter a user name and password, simply click a login button, type in numbers from a pre-paid ticket, or enter any other credentials that the network administrators require. The user then enters their credentials, which are checked by the access point or another server on the network. All other network access is blocked until these credentials are verified.

The users credentials are verified before further network access is granted. The authentication server can be the access point itself, another machine on the local network, or a server anywhere on the Internet. Once authenticated, the user is permitted to access network resources, and is typically redirected to the site they originally requested.

After authenticating, the user is permitted to access the rest of the network. Captive portals provide no encryption for the wireless users, instead relying on the MAC and IP address of the client as a unique identifier. Since this is not necessarily very secure, many implementations will require the user to re-authenticate periodically. This can often be automatically done by minimizing a special pop-up browser window when the user first logs in. Since they do not provide strong encryption, captive portals are not a very good choice for networks that need to be locked down to only allow access from trusted users. They are much more suited to cafes, hotels, and other public access locations where casual network users are expected. In public or semi-public network settings, encryption techniques such as WEP and WPA are effectively useless. There is simply no way to distribute public or shared keys to members of the general public without compromising the security of those keys. In these settings, a simple application such as a captive portal provides a level of service somewhere between completely open and completely closed.

Popular hotspot projects Chillispot (http://www.chillispot.info/). Chillispot is a captive portal designed to authenticate against an existing user credentials database, such as RADUIS. Combined with the application phpMyPrePaid, pre-paid ticket based authentication can be implemented very easily you can download phpMyPrePaid from http://sourceforge.net/projects/phpmyprepaid/. WiFi Dog (http://www.wifidog.org/). WiFi Dog provides a very complete captive portal authentication package in very little space (typically under 30kb). From a users perspective, it requires no pop-up or javascript support, allowing it to work on a wider variety of wireless devices. m0n0wall (http://m0n0.ch/wall/). m0n0wall is a complete embedded operating system based on FreeBSD. It includes a captive portal with RADIUS support, as well as a PHP web server. NoCatSplash (http://nocat.net/download/NoCatSplash/) provides a customizable splash page to your users, requiring them to click a login button before using the network. This is useful for identifying the operators of the network and displaying rules for network access. It provides a very easy solution in situations where you need to provide users of an open network with information and an acceptable use policy. Privacy Most users are blissfully unaware that their private email, chat conversations, and even passwords are often sent in the clear over dozens of untrusted networks before arriving at their ultimate destination on the Internet. However mistaken they may be, users still typically have some expectation of privacy when using computer networks. Privacy can be achieved, even on untrusted networks such as public access points and the Internet. The only proven effective method for protecting privacy is the use of strong end-to-end encryption. Encryption techniques such as WEP and WPA attempt to address the privacy issue at layer two, the data-link layer. This does protect against eavesdroppers listening in on the wireless connection, but this protection ends at the access point. If the wireless client uses insecure protocols (such as POP or simple SMTP for receiving and sending email), then users beyond the AP can still log the session and see the sensitive data. As mentioned earlier, WEP also suffers from the fact that it uses a shared private key. This means that legitimate wireless users can eavesdrop on each other, since they all know the private key. By using encryption to the remote end of the connection, users can neatly sidestep the entire problem. These techniques work well even on untrusted public networks, where eavesdroppers are listening and possibly even manipulating data coming from the access point. To ensure data privacy, good end-to-end encryption should provide the following features:

Verified authentication of the remote end. The user should be able to know without a doubt that the remote end is who it claims to be. Without authentication, a user could give sensitive data to anyone claiming to be the legitimate service. Strong encryption methods. The encryption algorithm should stand up to public scrutiny, and not be easily decrypted by a third party. There is no security in obscurity, and strong encryption is even stronger when the algorithm is widely known and subject to peer review. A good algorithm with a suitably large and protected key can provide encryption that is unlikely to be broken by any effort in our lifetimes using current technology. Public key cryptography. While not an absolute requirement for end-toend encryption, the use of public key cryptography instead of a shared key can ensure that an individual's data remains private, even if the key of another user of the service is compromised. It also solves certain problems with distributing keys to users over untrusted networks. Data encapsulation. A good end-to-end encryption mechanism protects as much data as possible. This can range from encrypting a single email transaction to encapsulation of all IP traffic, including DNS lookups and other supporting protocols. Some encryption tools simply provide a secure channel that other applications can use. This allows users to run any program they like and still have the protection of strong encryption, even if the programs themselves dont support it. Be aware that laws regarding the use of encryption vary widely from place to place. Some countries treat encryption as munitions, and may require a permit, escrow of private keys, or even prohibit its use altogether. Before implementing any solution that involves encryption, be sure to verify that use of this technology is permitted in your local area. In the following sections, well take a look at some specific tools that can provide good protection for your users data.

SSL The most widely available end-to-end encryption technology is Secure Sockets Layer, known simply as SSL. Built into virtually all web browsers, SSL uses public key cryptography and a trusted public key infrastructure (PKI) to secure data communications on the web. Whenever you visit a web URL that starts with https, you are using SSL. The SSL implementation built into web browsers includes a collection of certificates from trusted sources, called certificate authorities (CA). These certificates are cryptographic keys that are used to verify the authenticity of websites. When you browse to a website that uses SSL, the browser and the server first exchange certificates. The browser then verifies that the certificate provided by the server matches its DNS host name, that it has not expired, and that it is signed by a trusted certificate authority. The server optionally verifies the identity of the browses certificate. If the certificates are approved, the browser and server then negotiate a master session key using the previously exchanged certificates to protect it. That key is then used to encrypt all communications until the browser disconnects. This kind of data encapsulation is known as a tunnel.

Eavesdroppers must break strong encryption to monitor traffic over an encrypted tunnel. The conversation inside the tunnel is identical to any other unencrypted conversation. The use of certificates with a PKI not only protects the communication from eavesdroppers, but also prevents so-called man-in-the-middle (MITM) attacks. In a man-in-the-middle attack, a malicious user intercepts all communication between the browser and the server. By presenting counterfeit certificates to both the browser and the server, the malicious user could carry on two simultaneous encrypted sessions. Since the malicious user knows the secret on both connections, it is trivial to observe and manipulate data passing between the server and the browser.

The man-in-the-middle effectively controls everything the user sees, and can record and manipulate all traffic. Without a public key infrastructure to verify the authenticity of keys, strong encryption alone cannot protect against this kind of attack. Use of a good PKI prevents this kind of attack. In order to be successful, the malicious user would have to present a certificate to the client that is signed by a trusted certificate authority. Unless a CA has been compromised (very unlikely) or the user is tricked into accepting the forged certificate, then such an attack is not possible. This is why it is vitally important that users understand that ignoring warnings about expired or improper certificates is very dangerous, especially when using wireless networks. By clicking the ignore button when prompted by their browser, users open themselves up to many potential attacks. SSL is not only used for web browsing. Insecure email protocols such as IMAP, POP, and SMTP can be secured by wrapping them in an SSL tunnel. Most modern email clients support IMAPS and POPS (secure IMAP and POP) as well as SSL/TLS protected SMTP. If your email server does not provide SSL support, you can still

secure it with SSL using a package like Stunnel (http://www.stunnel.org/). SSL can be used to effectively secure just about any service that runs over TCP.

SSH Most people think of SSH as a secure replacement for telnet, just as scp and sftp are the secure counterparts of rcp and ftp. But SSH is much more than encrypted remote shell. Like SSL, it uses strong public key cryptography to verify the remote server and encrypt data. Instead of a PKI, it uses a key fingerprint cache that is checked before a connection is permitted. It can use passwords, public keys, or other methods for user authentication. Many people do not know that SSH can also act as a general purpose encrypting tunnel, or even an encrypting web proxy. By first establishing an SSH connection to a trusted location near (or even on) a remote server, insecure protocols can be protected from eavesdropping and attack. While this technique may be a bit advanced for many users, network architects can use SSH to encrypt traffic across untrusted links, such as wireless point-to-point links. Since the tools are freely available and run over standard TCP, any educated user can implement SSH connections for themselves, providing their own end-to-end encryption without administrator intervention. OpenSSH (http://openssh.org/) is probably the most popular implementation on Unix-like platforms. Free implementations such as Putty (http://www.putty.nl/) and WinSCP (http://winscp.net/) are available for Windows. OpenSSH will also run on Windows under the Cygwin package (http://www.cygwin.com/). These examples will assume that you are using a recent version of OpenSSH.

The SSH tunnel protects web traffic up to the SSH server itself. To establish an encrypted tunnel from a port on the local machine to a port on the remote side, use the -L switch. For example, suppose you want to forward web proxy traffic over an encrypted link to the squid server at squid.example.net. Forward port 3128 (the default proxy port) using this command: ssh -fN -g -L3128:squid.example.net:3128 squid.example.net The -fN switches instruct ssh to fork into the background after connecting. The -g switch allows other users on your local segment to connect to the local machine and use it for encryption over the untrusted link. OpenSSH will use a public key for authentication if you have set one up, or it will prompt you for your password on the remote side. You can then configure your web browser to connect to localhost port 3128 as its web proxy service. All web traffic will then be encrypted before transmission to the remote side. SSH can also act as a dynamic SOCKS4 or SOCKS5 proxy. This allows you to create an encrypting web proxy, without the need to set up squid. Note that this is not a caching proxy; it simply encrypts all traffic. ssh -fN -D 8080 remote.example.net Configure your web browser to use SOCKS4 or SOCKS5 on local port 8080, and away you go. SSH can encrypt data on any TCP port, including ports used for email. It can even compress the data along the way, which can decrease latency on low capacity links. ssh -fNCg -L110:localhost:110 -L25:localhost:25 mailhost.example.net

The -C switch turns on compression. You can add as many port forwarding rules as you like by specifying the -L switch multiple times. Note that in order to bind to a local port less than 1024, you must have root privileges on the local machine. These are just a few examples of the flexibility of SSH. By implementing public keys and using the ssh forwarding agent, you can automate the creation of encrypted tunnels throughout your wireless network, and protect your communications with strong encryption and authentication.

OpenVPN OpenVPN is a free, open source VPN implementation built on SSL encryption. There are OpenVPN client implementations for a wide range of operating systems, including Linux, Windows 2000/XP and higher, OpenBSD, FreeBSD, NetBSD, Mac OS X, and Solaris. Being a VPN, it encapsulates all traffic (including DNS and all other protocols) in an encrypted tunnel, not just a single TCP port. Most people find it considerably easier to understand and configure than IPSEC. OpenVPN also has some disadvantages, such as fairly high latency. Some amount of latency is unavoidable since all encryption/decryption is done in user space, but using relatively new computers on either end of the tunnel can minimize this. While it can use traditional shared keys, OpenVPN really shines when used with SSL certificates and a certificate authority. OpenVPN has many advantages that make it a good option for providing end-to-end security. Some of these reasons include: It is based on a proven, robust encryption protocol (SSL and RSA) It is relatively easy to configure It functions across many different platforms It is well documented It's free and open source. OpenVPN needs to connect to a single TCP or UDP port on the remote side. Once established, it can encapsulate all data down to the Networking layer, or even down to the Data-Link layer, if your solution requires it. You can use it to create robust VPN connections between individual machines, or simply use it to connect network routers over untrusted wireless networks. VPN technology is a complex field, and is a bit beyond the scope of this section to go into more detail. It is important to understand how VPNs fit into the structure of your network in order to provide the best possible protection without opening up your organization to unintentional problems. There are many good online resources that deal with installing OpenVPN on a server and client, we recommend this article from Linux Journal: http://www.linuxjournal.com/article/7949 as well as the official HOWTO: http://openvpn.net/howto.html

Tor & Anonymizers The Internet is basically an open network based on trust. When you connect to a web server across the Internet, your traffic passes through many different routers, owned by a great variety of institutions, corporations and individuals. In principle, any one of these routers has the ability to look closely at your data, seeing the source and destination addresses, and quite often also the actual content of the data. Even if your data is encrypted using a secure protocol, it is possible for your Internet provider to monitor the amount of data transferred, as well as the source and destination of that data. Often this is enough to piece together a fairly complete picture of your activities on-line. Privacy and anonymity are important, and closely linked to each other. There are many valid reasons to consider protecting your privacy by anonymizing your network traffic. Suppose you want to offer Internet connectivity to your local community by setting up a number of access points for people to connect to. Whether you charge them for their access or not, there is always the risk that people use the network for something that is not legal in your country or region. You could plead with the legal system that this particular illegal action was not performed by yourself, but could have been performed by anyone connecting to your network. The problem is neatly sidestepped if it were technically infeasible to determine where your traffic was actually headed. And what about on-line censorship? Publishing web pages anonymously may also be necessary to avoid government censorship. There are tools that allow you to anonymize your traffic in relatively easy ways. The combination of Tor (http://www.torproject.org/) and Privoxy (http://www.privoxy.org/) is a powerful way to run a local proxy server that will pass your Internet traffic through a number of servers all across the net, making it very difficult to follow the trail of information. Tor can be run on a local PC, under Microsoft Windows, Mac OSX, Linux and a variety of BSD's, where it anonymizes traffic from the browser on that particular machine. Tor and Privoxy can also be installed on a gateway server, or even a small embedded access point (such as a Linksys WRT54G) where they provides anonymity to all network users automatically. Tor works by repeatedly bouncing your TCP connections across a number of servers spread throughout the Internet, and by wrapping routing information in a number of encrypted layers (hence the term onion routing), that get peeled off as the packet moves across the network. This means that, at any given point in the network, the source and destination addresses cannot be linked together. This makes traffic analysis extremely difficult. The need for the Privoxy privacy proxy in connection with Tor is due to the fact that name server queries (DNS queries) in most cases are not passed through the proxy server, and someone analyzing your traffic would easily be able to see that you were trying to reach a specific site (say google.com) by the fact that you sent a DNS query to translate google.com to the appropriate IP address. Privoxy connects to Tor as a SOCKS4a proxy, which uses hostnames (not IP addresses) to get your packets to the intended destination.

In other words, using Privoxy with Tor is a simple and effective way to prevent traffic analysis from linking your IP address with the services you use online. Combined with secure, encrypted protocols (such as those we have seen already), Tor and Privoxy provide a high level of anonymity on the Internet.

Network Monitoring Network monitoring is the use of logging and analysis tools to accurately determine traffic flows, utilization, and other performance indicators on a network. Good monitoring tools give you both hard numbers and graphical aggregate representations of the state of the network. This helps you to visualize precisely what is happening, so you know where adjustments may be needed. These tools can help you answer critical questions, such as: What are the most popular services used on the network? Who are the heaviest network users? What other wireless channels are in use in my area? Are users installing wireless access points on my private wired network? At what time of the day is the network most utilized? What sites do your users frequent? Is the amount of inbound or outbound traffic close to our available network capacity? Are there indications of an unusual network situation that is consuming bandwidth or causing other problems? Is our Internet Service Provider (ISP) providing the level of service that we are paying for? This should be answered in terms of available bandwidth, packet loss, latency, and overall availability. And perhaps the most important question of all: Do the observed traffic patterns fit our expectations? Let's look at how a typical system administrator can make good use of network monitoring tools.

An effective network monitoring example For the purposes of example, let's assume that we are in charge of a network that has been running for three months. It consists of 50 computers and three servers: email, web, and proxy servers. While initially things are going well, users begin to complain of slow network speeds and an increase in spam emails. As time goes on, computer performance slows to a crawl (even when not using the network), causing considerable frustration in your users. With frequent complaints and very low computer usage, the Board is questioning the need for so much network hardware. The Board also wants evidence that the bandwidth they are paying for is actually being used. As the network administrator, you are on the receiving end of these complaints. How can you diagnose the sudden drop in network and computer performance and also justify the network hardware and bandwidth costs?

Monitoring the LAN (local traffic) To get an idea of exactly what is causing the slow down, you should begin by looking at traffic on the local LAN. There are several advantages to monitoring local traffic: Troubleshooting is greatly simplified. Viruses can be detected and eliminated. Malicious users can be detected and dealt with. Network hardware and resources can be justified with real statistics. Assume that all of the switches support the Simple Network Management Protocol (SNMP). SNMP is an application-layer protocol designed to facilitate the exchange of management information between network devices. By assigning an IP address to each switch, you are able to monitor all the interfaces on that switch, observing the entire network from a single point. This is much easier than enabling SNMP on all computers in a network.By using a free tool such as MRTG (see Page 190), you can monitor each port on the switch and present data graphically, as an aggregate average over time. The graphs are accessible from the web, so you are able to view the graphs from any machine at anytime. With MRTG monitoring in place, it becomes obvious that the internal LAN is swamped with far more traffic than the Internet connection can support, even when the lab is unoccupied. This is a pretty clear indication that some of the computers are infested with a network virus. After installing good anti-virus and anti-spyware software on all of the machines, the internal LAN traffic settles down to expected levels. The machines run much more quickly, spam emails are reduced, and the users' morale quickly improves.

Monitoring the WAN (external traffic) In addition to watching the traffic on the internal LAN, you need to demonstrate that the bandwidth the organization is paying for is actually what they are getting from their ISP. You can achieve this by monitoring external traffic. External traffic is generally classified as anything sent over a Wide Area Network (WAN). Anything received from (or sent to) a network other than your internal LAN also qualifies as external traffic. The advantages of monitoring external traffic include: Internet bandwidth costs are justified by showing actual usage, and whether that usage agrees with your ISP's bandwidth charges. Future capacity needs are estimated by watching usage trends and predicting likely growth patterns. Intruders from the Internet are detected and filtered before they can cause problems. Monitoring this traffic is easily done with the use of MRTG on an SNMP enabled device, such as a router. If your router does not support SNMP, then you can add a switch between your router and your ISP connection, and monitor the port traffic just as you would with an internal LAN.

Detecting Network Outages With monitoring tools in place, you now have an accurate measurement of how much bandwidth the organization is using. This measurement should agree with your ISP's bandwidth charges. It can also indicate the actual throughput of your connection if you are using close to your available capacity at peak times. A "flat top" graph is a fairly clear indication that you are operating at full capacity. Figure below shows flat tops in peak outbound traffic in the middle of every day except Sunday. It is clear that your current Internet connection is overutilized at peak times, causing network lag. After presenting this information to the Board, you can make a plan for further optimizing your existing connection (by upgrading your proxy server and using other techniques in this book) and estimate how soon you will need to upgrade your connection to keep up with the demand. This is also an excellent time to review your operational policy with theBoard, and discuss ways to bring actual usage in line with that policy.

A graph with a "flat top" is one indication of overutilization Later in the week, you receive an emergency phone call in the evening. Apparently, no one in the lab can browse the web or send email. You rush to the lab and hastily reboot the proxy server, with no results. Browsing and email are still broken. You then reboot the router, but there is still no success. You continue eliminating the possible fault areas one by one until you realize that the network switch is off - a loose power cable is to blame. After applying power, the network comes to life again. How can you troubleshoot such an outage without such time consuming trial and error? Is it possible to be notified of outages as they occur, rather than waiting for a user to complain? One way to do this is to use a program such as Nagios that continually polls network devices and notifies you of outages. Nagios will report on the availability of various machines

and services, and will alert you to machines that have gone down. In addition to displaying the network status graphically on a web page, it will send notifications via SMS or email, alerting you immediately when problems arise. With good monitoring tools in place, you will be able to justify the cost of equipment and bandwidth by effectively demonstrating how it is being used by the organization. You are notified automatically when problems arise, and you have historical statistics of how the network devices are performing. You can check the current performance against this history to find unusual behavior, and head off problems before they become critical. When problems do come up, it is simple to determine the source and nature of the problem.Your job is easier, the Board is satisfied, and your users are much happier.

Monitoring your network Managing a network without monitoring is similar to driving a vehicle without a speedometer or a fuel gauge, with your eyes closed. How do you know how fast you are going? Is the car consuming fuel as efficiently as promised by the dealers? If you do an engine overhaul several months later, is the car any faster or more efficient than it was before? Similarly, how can you pay for an electricity or water bill without seeing your monthly usage from a meter? You must have an account of your network bandwidth utilization in order to justify the cost of services and hardware purchases, and to account for usage trends. There are several benefits to implementing a good monitoring system for your network: 1. Network budget and resources are justified. Good monitoring tools can demonstrate without a doubt that the network infrastructure (bandwidth, hardware, and software) is suitable and able to handle the requirements of network users. 2. Network intruders are detected and filtered. By watching your network traffic, you can detect attackers and prevent access to critical internal servers and services. 3. Network viruses are easily detected. You can be alerted to the presence of network viruses, and take appropriate action before they consume Internet bandwidth and destabilize your network. 4. Troubleshooting of network problems is greatly simplified. Rather than attempting "trial and error" to debug network problems, you can be instantly notified of specific problems. Some kinds of problems can even be repaired automatically. 5. Network performance can be highly optimized. Without effective monitoring, it is impossible to fine tune your devices and protocols to achieve the best possible performance. 6. Capacity planning is much easier. With solid historical performance records, you do not have to "guess" how much bandwidth you will need as your network grows.

7. Proper network usage can be enforced. When bandwidth is a scarce resource, the only way to be fair to all users is to ensure that the network is being used for its intended purpose. Fortunately, network monitoring does not need to be an expensive undertaking. There are many freely available open source tools that will show you exactly what is happening on your network in considerable detail. This section will help you identify many invaluable tools and how best to use them.

The dedicated monitoring server While monitoring services can be added to an existing network server, it is often desirable to dedicate one machine (or more, if necessary) to network monitoring. Some applications (such as ntop) require considerable resources to run, particularly on a busy network. But most logging and monitoring programs have modest RAM and storage requirements, typically with little CPU power required. Since open source operating systems (such as Linux or BSD) make very efficient use of hardware resources, this makes it possible to build a very capable monitoring server from recycled PC parts. There is usually no need to purchase a brand new server to relegate to monitoring duties. The exception to this rule is in very large installations. If your network includes more than a few hundred nodes, or if you consume more than 50 Mbps of Internet bandwidth, you will likely need to split up monitoring duties between a few dedicated machines. This depends largely on exactly what you want to monitor. If you are attempting to account for all services accessed per MAC address, this will consume considerably more resources than simply measuring network flows on a switch port. But for the majority of installations, a single dedicated monitoring machine is usually enough. While consolidating monitoring services to a single machine will streamline administration and upgrades, it can also ensure better ongoing monitoring. For example, if you install monitoring services on a web server, and that web server develops problems, then your network may not be monitored until the problem is resolved. To a network administrator, the data collected about network performance is nearly as important as the network itself. Your monitoring should be robust and protected from service outages as well as possible. Without network statistics, you are effectively blind to problems with the network.

Where does the server fit in my network? If you are only interested in collecting network flow statistics from a router, you can do this from just about anywhere on the LAN. This provides simple feedback about utilization, but cannot give you comprehensive details about usage patterns. Figure below shows a typical MRTG graph generated from the Internet router. While the inbound and outbound utilization are clear, there is no detail about which computers, users, or protocols are using bandwidth.

Polling the edge router can show you the overall network utilization, but you cannot break the data down further into machines, services, and users. For more detail, the dedicated monitoring server must have access to everything that needs to be watched. Typically, this means it must have access to the entire network. To monitor a WAN connection, such as the Internet link to your ISP, the monitoring server must be able to see the traffic passing through the edge router. To monitor a LAN, the monitoring server is typically connected to a monitor port on the switch. If multiple switches are used in an installation, the monitoring server may need a connection to all of them. That connection can either be a physical cable, or if your network switches support it, a VLAN specifically configured for monitoring traffic.

Use the monitor port on your switch to observe traffic crossing all of the network ports
.

If monitor port functionality is not available on your switch, the monitoring server may be installed between your internal LAN and the Internet. While this will work, it introduces a single point of failure for the network, as the network will fail if the monitoring server develops a problem. It is also a potential performance bottleneck, if the server cannot keep up with the demands of the network.

By inserting a network monitor between the LAN and your Internet connection, you can observe all network traffic. A better solution is to use a simple network hub (not a switch) which connects the monitoring machine to the internal LAN, external router, and the monitoring machine. While this does still introduce an additional point of failure to the network (since the entire network will be unreachable if the hub dies), hubs are generally considered to be much more reliable than routers.They are also very easily replaced should they fail.

If your switch does not provide monitor port functionality, you can insert a network hub between your Internet router and the LAN, and connect the monitoring server to the hub. Once your monitoring server is in place, you are ready to start collecting data.

What to monitor It is possible to plot just about any network event and watch its value on a graph over time. Since every network is slightly different, you will have to decide what information is important in order to gauge the performance of your network. Here are some important indicators that many network administrators will typically track.

Wireless statistics Received signal and noise from all backbone nodes Number of associated stations Detected adjacent networks and channels Excessive retransmissions Radio data rate, if using automatic rate scaling

Switch statistics Bandwidth usage per switch port Bandwidth usage broken down by protocol Bandwidth usage broken down by MAC address Broadcasts as a percentage of total packets Packet loss and error rate

Internet statistics Internet bandwidth use by host and protocol Proxy server cache hits Top 100 sites accessed DNS requests Number of inbound emails / spam emails / email bounces Outbound email queue size Availability of critical services (web servers, email servers, etc.). Ping times and packet loss rates to your ISP Status of backups

System health statistics Memory usage Swap file usage Process count / zombie processes System load Uninterruptible Power Supply (UPS) voltage and load Temperature, fan speed, and system voltages Disk SMART status RAID array status You should use this list as a suggestion of where to begin. As your network matures, you will likely find new key indicators of network performance, and you should of course track those as well. There are many freely available tools that will show you as much detail as you like about what is happening on your network. You should consider monitoring the availability of any resource where unavailability would adversely affect your network users. For example, your users may dial into modems on your site to gain remote access to your network. If all the modems are used, or if any are faulty, then users will be denied access and will probably complain. You can predict and avoid such problems by monitoring the number of available modems, and provisioning extra capacity before you run out. Don't forget to monitor the monitoring machine itself, for example its CPU usage and disk space, in order to receive advance warning if it becomes overloaded or faulty. A monitoring machine that is low on resources can affect your ability to monitor the network effectively.

Types of monitoring tools We will now look at several different classes of monitoring tools. Network detection tools listen for the beacons sent by wireless access points, and display information such as the network name, received signal strength, and channel. Spot check tools are designed for troubleshooting and normally run interactively for short periods of time. A program such as ping may be considered an active spot check tool, since it generates traffic by polling a particular machine. Passive spot check tools include protocol analyzers, which inspect every packet on the network and provide complete detail about any network conversation (including source and destination addresses, protocol information, and even application data). Trending tools perform unattended monitoring over long periods, and typically plot the results on a graph. Realtime monitoring tools perform similar monitoring, but notify administrators immediately if they detect a problem. Throughput testing tools tell you the actual bandwidth available between two points on a network. Intrusion detection tools watch for undesirable or unexpected network traffic, and take Appropriate action (typically denying access and/or notifying a network administrator). Finally, benchmarking tools estimate the maximum performance of a service or network connection.

Network detection The simplest wireless monitoring tools simply provide a list of available networks, along with basic information (such as signal strength and channel). They let you quickly detect nearby networks and determine if they are in range or are causing interference. The built-in client. All modern operating systems provide built-in support for wireless networking. This typically includes the ability to scan for available networks, allowing the user to choose a network from a list. While virtually all wireless devices are guaranteed to have a simple scanning utility, functionality can vary widely between implementations. These tools are typically only useful for configuring a computer in a home or office setting. They tend to provide little information apart from network names and the available signal to the access point currently in use. Netstumbler (http://www.netstumbler.com/). This is the most popular tool for detecting wireless networks using Microsoft Windows. It supports a variety of wireless cards, and is very easy to use. It will detect open and encrypted networks, but cannot detect closed wireless networks. It also features a signal/noise meter that plots radio receiver data as a graph over time. It also integrates with a variety of GPS devices, for logging precise location and signal strength information. This makes Netstumbler a handy tool to have for an informal site survey. Ministumbler (http://www.netstumbler.com/). From the makers of Netstumbler, Ministumbler provides much of the same functionality as the Windows version, but works on the Pocket PC platform. inistumbler is handy to run on a handheld PDA with a wireless card for detecting access points in the field. Macstumbler (http://www.macstumbler.com/). While not directly related to the Netstumbler, Macstumbler provides much of the same functionality but for the Mac OS X platform. It works with all Apple Airport cards. Wellenreiter (http://www.wellenreiter.net/). Wellenreiter is a nice graphical wireless network detector for Linux. It requires Perl and GTK, and supports Prism2, Lucent, and Cisco wireless cards.

Spot check tools What do you do when the network breaks? If you cant access a web page or email server, and clicking the reload button doesnt fix the problem, then youll need to be able to isolate the exact location of the problem. These tools will help you to determine just where a connection problem exists. This section is simply an introduction to commonly used troubleshooting tools. For more discussion of common network problems and how to diagnose them, see, Troubleshooting.

Ping Just about every operating system (including Windows, Mac OS X, and of course Linux and BSD) includes a version of the ping utility. It uses ICMP packets to attempt to contact a specified host, and tells you how long it takes to get a response. Knowing what to ping is just as important as knowing how to ping. If you find that you cannot connect to a particular service in your web browser (say, http://yahoo.com /), you could try to ping it: $ ping yahoo.com PING yahoo.com (66.94.234.13): 56 data bytes 64 bytes from 66.94.234.13: icmp_seq=0 ttl=57 time=29.375 ms 64 bytes from 66.94.234.13: icmp_seq=1 ttl=56 time=35.467 ms 64 bytes from 66.94.234.13: icmp_seq=2 ttl=56 time=34.158 ms ^C --- yahoo.com ping statistics --3 packets transmitted, 3 packets received, 0% packet loss round-trip min/avg/max/stddev = 29.375/33.000/35.467/2.618 ms Hit control-C when you are finished collecting data. If packets take a long time to come back, there may be network congestion. If return ping packets have an unusually low Time To Live (TTL), you may have routing problems between your machine and the remote end. But what if the ping doesnt return any data at all? If you are pinging a name instead of an IP address, you may be running into DNS problems. Try pinging an IP address on the Internet. If you cant reach it, its a good idea to see if you can ping your default router: $ ping 69.90.235.230 PING 69.90.235.230 (69.90.235.230): 56 data bytes 64 bytes from 69.90.235.230: icmp_seq=0 ttl=126 time=12.991 ms 64 bytes from 69.90.235.230: icmp_seq=1 ttl=126 time=14.869 ms 64 bytes from 69.90.235.230: icmp_seq=2 ttl=126 time=13.897 ms ^C --- 216.231.38.1 ping statistics --3 packets transmitted, 3 packets received, 0% packet loss round-trip min/avg/max/stddev = 12.991/13.919/14.869/0.767 ms If you cant ping your default router, then chances are you wont be able to get to the Internet either. If you cant even ping other IP addresses on your local LAN, then its time to check your connection. If youre using Ethernet, is it plugged in? If youre using wireless, are you connected to the proper wireless network, and is it in range? Network debugging with ping is a bit of an art, but it is useful to learn. Since you will likely find ping on just about any machine you will work on, Its a good idea to learn how to use it well.

Traceroute and mtr http://www.bitwizard.nl/mtr/. As with ping, traceroute is found on most operating systems (its called tracert in some versions of Microsoft Windows). By running traceroute, you can find the location of problems between your computer and any point on the Internet: $ traceroute -n google.com traceroute to google.com (72.14.207.99), 64 hops max, 40 byte packets 1 10.15.6.1 4.322 ms 1.763 ms 1.731 ms 2 216.231.38.1 36.187 ms 14.648 ms 13.561 ms 3 69.17.83.233 14.197 ms 13.256 ms 13.267 ms 4 69.17.83.150 32.478 ms 29.545 ms 27.494 ms 5 198.32.176.31 40.788 ms 28.160 ms 28.115 ms 6 66.249.94.14 28.601 ms 29.913 ms 28.811 ms 7 172.16.236.8 2328.809 ms 2528.944 ms 2428.719 ms 8*** The -n switch tells traceroute not to bother resolving names in DNS, and makes the trace run more quickly. You can see that at hop seven, the round trip time shoots up to more than two seconds, while packets seem to be discarded at hop eight. This might indicate a problem at that point in the network. If this part of the network is in your control, it might be worth starting your troubleshooting effort there. My TraceRoute (mtr) is a handy program that combines ping and traceroute into a single tool. By running mtr, you can get an ongoing average of latency and packet loss to a single host, instead of the momentary snapshot that ping and traceroute provide.
tesla.rob.swn (0.0.0.0) Keys: Help Display mode My traceroute [v0.69] (tos=0x0 psize=64 bitpatSun Jan 8 20:01:26 2006 Restart statistics Order of fields quit Packets Pings Host Loss% Snt Last Avg Best Wrst StDev 1. gremlin.rob.swn 0.0% 4 1.9 2.0 1.7 2.6 0.4 2. er1.sea1.speakeasy.net 0.0% 4 15.5 14.0 12.7 15.5 1.3 3. 220.ge-0-1-0.cr2.sea1.speakeasy. 0.0% 4 11.0 11.7 10.7 14.0 1.6 4. fe-0-3-0.cr2.sfo1.speakeasy.net 0.0% 4 36.0 34.7 28.7 38.1 4.1 5. bas1-m.pao.yahoo.com 0.0% 4 27.9 29.6 27.9 33.0 2.4 6. so-1-1-0.pat1.dce.yahoo.com 0.0% 4 89.7 91.0 89.7 93.0 1.4 7. ae1.p400.msr1.dcn.yahoo.com 0.0% 4 91.2 93.1 90.8 99.2 4.1 8. ge5-2.bas1-m.dcn.yahoo.com 0.0% 4 89.3 91.0 89.3 93.4 1.9 9. w2.rc.vip.dcn.yahoo.com 0.0% 3 91.2 93.1 90.8 99.2 4.1

The data will be continuously updated and averaged over time. As with ping, you should hit control-C when you are finished looking at the data. Note that you must have root privileges to run mtr. While these tools will not revel precisely what is wrong with the network, they can give you enough information to know where to continue troubleshooting.

Protocol analyzers Network protocol analyzers provide a great deal of detail about information flowing through a network, by allowing you to inspect individual packets. For wired networks, you can inspect packets at the data-link layer or above. For wireless networks, you can inspect information all the way down to individual 802.11 frames. Here are several popular (and free) network protocol analyzers:

Kismet http://www.kismetwireless.net/. Kismet is a powerful wireless protocol analyzer for many platforms including Linux, Mac OS X, and even the embedded OpenWRT Linux distribution. It works with any wireless card that supports passive monitor mode. In addition to basic network detection, Kismet will passively log all 802.11 frames to disk or to the network in standard PCAP format, for later analysis with tools like Ethereal. Kismet also features associated client information, AP hardware fingerprinting, Netstumbler detection, and GPS integration. Since it is a passive network monitor, it can even detect closed wireless networks by analyzing traffic sent by wireless clients. You can run Kismet on several machines at once, and have them all report over the network back to a central user interface. This allows for wireless monitoring over a large area, such as a university or corporate campus.

Kismet running on a Nokia 770 Internet Tablet Since Kismet uses the radio card's passive monitor mode, it does all of this without transmitting any data. Kismet is an invaluable tool for diagnosing wireless network problems. KisMAC http://kismac.macpirate.ch/. Exclusively for the Mac OS X platform, KisMAC does much of what Kismet can do, but with a slick Mac OS X graphical interface. It is a passive scanner that will log data to disk in PCAP format compatible with Wireshark. It supports passive scanning with AirportExtreme cards as well as a variety of USB wireless adapters.

Tcpdump http://www.tcpdump.org/. tcpdump is a command-line tool for monitoring network traffic. It does not have all the bells and whistles of wireshark but it does use fewer resources. Tcpdump can capture and display all network protocolinformation down to the link layer. It can show all of the packet headers and data received, or just the packets that match particular criteria. Packets captured with tcpdump can be loaded into wireshark for visual analysis and further diagnostics. This is very useful if you wish to monitor an interface on a remote system and bring the file back to your local machine for analysis. Thetcpdump tool is available as a standard tool in Unix derivatives (Linux, BSD, and Mac OS X). There is also a Windows port called WinDump available at http://www.winpcap.org/windump/.

Wireshark http://www.wireshark.org/. Formerly known as Ethereal, Wireshark is a free network protocol analyzer for Unix and Windows. It is billed as "The World's Most Popular Network Protocol Analyzer."

Wireshark (formerly Ethereal) is a powerful network protocol analyzer that can show you as much detail as you like about any packet.

Wireshark allows you to examine data from a live network or from a capture file on disk, and interactively browse and sort the captured data. Both summary and detailed information is available for each packet, including the full header and data portions. Wireshark has several powerful features, including a rich display filter language and the ability to view the reconstructed stream of a TCP session. It can be daunting to use for first time users or those that are not familiar with the OSI layers. It is typically used to isolate and analyze specific traffic to or from an IP address, but it can be also used as a general purpose fault finding tool. For example, a machine infected with a network worm or virus can be identified by looking for the machine that is send out the same sort of TCPIP packets to large groups of IP addresses.

Trending tools Trending tools are used to see how your network is used over a long period of time. They work by periodically monitoring your network activity, and displaying a summary in a humanreadable form (such as a graph). Trending tools collect data as well as analyze and report on it. Below are some examples of trending tools. Some of them need to be used in conjunction with each other, as they are not stand-alone programs. MRTG http://oss.oetiker.ch/mrtg/. The Multi Router Traffic Grapher (MRTG) monitors the traffic load on network links using SNMP. MRTG generates graphs that provide a visual representation of inbound and outbound traffic. These are typically displayed on a web page. MRTG can be a little confusing to set up, especially if you are not familiar with SNMP. But once it is installed, MRTG requires virtually no maintenance, unless you change something on the system that is being monitored (such as its IP address).

MRTG is probably the most widely installed network flow grapher

RRDtool http://oss.oetiker.ch/rrdtool/. RRD is short for Round Robin Database. RRD is a database that stores information in a very compact way that does not expand over time. RRDtool refers to a suite of tools that allow you to create and modify RRD databases, as well as generate useful graphs to present the data. It is used to keep track of time-series data (such as network bandwidth, machine room temperature, or server load average) and can display that data as an average over time. Note that RRDtool itself does not contact network devices to retrieve data. It is merely a database manipulation tool. You can use a simple wrapper script (typically in shell or Perl) to do that work for you. RRDtool is also used by many full featured front-ends that present you with a friendly web interface for configuration and display. RRD graphs give you more control over display options and the number of items available on a graph as compared to MRTG.

RRDtool gives you a lot of flexibility in how your collected network data may be displayed. RRDtool is included in virtually all modern Linux distributions, and can be downloaded from http://oss.oetiker.ch/rrdtool/.

Ntop http://www.ntop.org/. For historical traffic analysis and usage, you will certainly want to investigate ntop. This program builds a detailed real-time report on observed network traffic, displayed in your web browser. It integrates with rrdtool, and makes graphs and charts visually depicting how the network is being used. On very busy networks, ntop can use a lot of CPU and disk space, but it gives you extensive insight into how your network is being used. It runs on Linux, BSD, Mac OS X, and Windows. Some of its more useful features include: Traffic display can be sorted by various criteria (source, destination, protocol, MAC address, etc.). Traffic statistics grouped by protocol and port number An IP traffic matrix which shows connections between machines Network flows for routers or switches that support the NetFlow protocol Host operating system identification P2P traffic identification Numerous graphical charts Perl, PHP, and Python API

Ntop is available from http://www.ntop.org/ and is available for most operating systems. It is often included in many of the popular Linux distributions, including RedHat, Debian, and Ubuntu. While it can be left running to collect historical data, ntop can be fairly CPU intensive, depending on the amount of traffic observed. If you are going to run it for long periods you should monitor the CPU utilization of the monitoring machine.

ntop displays a wealth of information about how your network is utilized by various clients and servers. The main disadvantage of ntop is that it does not provide instantaneous information, only longterm totals and averages. This can make it difficult to use to diagnose a problem that starts suddenly.

Cacti http://www.cacti.net/. Cacti is a front-end for RRDtool. It stores all of the necessary information to create graphs in a MySQL database. The front-end is written in PHP. Cacti does the work of maintaining graphs, data sources, and handles the actual data gathering. There is support for SNMP devices, and custom scripts can easily be written to poll virtually any conceivable network event.

Cacti can manage the polling of your network devices, and can build very complex and informative visualizations of network behavior. Cacti can be somewhat confusing to configure, but once you work through the documentation and examples, it can yield very impressive graphs. There are hundreds of templates for various systems available on the cacti website, and the code is under rapid development.

NetFlow NetFlow is a protocol for collecting IP traffic information invented by Cisco. From the Cisco website: Cisco IOS NetFlow efficiently provides a key set of services for IP applications, including network traffic accounting, usage-based network billing, network planning, security, Denial of Service monitoring capabilities, and network monitoring. NetFlow provides valuable information about network users and applications, peak usage times, and traffic routing. Cisco routers can generate NetFlow information which is available from the router in the form of UDP packets. NetFlow is also less CPU-intensive on Cisco routers than using SNMP. It also provides more granular information than SNMP, letting you get a more detailed picture of port and protocol usage.

This information is collected by a NetFlow collector that stores and presents the data as an aggregate over time. By analyzing flow data, one can build a picture of traffic flow and traffic volume in a network or on a connection. There are several commercial and free NetFlow collectors available. Ntop is one free tool that can act as a NetFlow collector and probe. Another is Flowc (see below). It can also be desirable to use Netflow as a spot check tool, by just looking at a quick snapshot of data during a network crisis. Think of NetFlow as an alternative to SNMP for Cisco devices. For more information about NetFlow, see http://en.wikipedia.org/wiki/Netflow .

Flowc http://netacad.kiev.ua/flowc/. Flowc is an open source NetFlow collector (see NetFlow above). It is lightweight and easy to configure. Flowc uses a MySQL database to store aggregated traffic information. Therefore, it is possible to generate your own reports from the data using SQL, or use the included report generators. The built-in report generators produce reports in HTML, plain text or a graphical format.

A typical flow chart generated by Flowc The large gap in data probably indicates a network outage. Trending tools typically will not notify you of outages, but merely log the occurrence. To be notified when network problems occur, use a realtime monitoring tool such as Nagios.

SmokePing http://oss.oetiker.ch/smokeping/. SmokePing is a deluxe latency measurement tool written in Perl. It can measure, store and display latency, latency distribution and packet loss all on a single graph. SmokePing uses RRDtool for data storage, and can draw very informative graphs that present up to the minute information on the state of your network connection.

It is very useful to run SmokePing on a host with good connectivity to your entire network. Over time, trends are revealed that can point to all sorts of network problems. Combined with MRTG or Cacti , you can observe the effect that network congestion has on packet loss and latency. SmokePing can optionally send alerts when certain conditions are met, such as when excessive packet loss is seen on a link for an extended period of time. An example of SmokePing in action is shown in Figure below.

SmokePing can simultaneously display packet loss and latency spreads in a single graph.

EtherApe http://etherape.sourceforge.net/. EtherApe displays a graphical representation of network traffic. Hosts and links change size depending on the amount of traffic sent and received. The colors change to represent the protocol most used. As with wireshark and tcpdump, data can be captured "off the wire" from a live network connection or read from a tcpdump capture file. EtherApe doesn't show quite as much detail as ntop, but its resource requirements are much lighter.

Iptraf http://iptraf.seul.org/. IPTraf is a lightweight but powerful LAN monitor. It has an ncurses interface and runs in a command shell. IPTraf takes a moment to measure observed traffic, and then displays various network statistics including TCP and UDP connections, ICMP and OSPF information, traffic flows, IP checksum errors, and more. It is a simple to use program that uses minimal system resources. While it does not keep historical data, it is very useful for displaying an instantaneous usage report.

iptraf's statistical breakdown of traffic by port Argus http://qosient.com/argus/. Argus stands for Audit Record Generation and Utilization System. Argus is also the name of the mythological Greek god who had hundreds of eyes. From the Argus website: Argus generates flow statistics such as connectivity, capacity, demand, loss, delay, and jitter on a per transaction basis. Argus can be used to analyze and report on the contents of packet capture files or it can run as a continuous monitor, examining data from a live interface; generating an audit log of all the network activity seen in the packet stream. Argus can be deployed to monitor individual end-systems, or an entire enterprises network activity. As a continuous monitor, Argus provides both push and pull data handling models, to allow flexible strategies for collecting network audit data. Argus data clients support a range of operations, such as sorting, aggregation, archival and reporting. Argus consists of two parts: a master collector that reads packets from a network device, and a client that connects to the master and displays the usage statistics. Argus runs on BSD, Linux, and most other UNIX systems.

NeTraMet http://freshmeat.net/projects/netramet/. NeTraMet is another popular flow analysis tool. Like Argus, NeTraMet consists of two parts: a collector that gathers statistics via SNMP, and a manager that specifies which flows should be watched. Flows are specified using a simple programming language that define the addresses used on either end, and can include Ethernet, IP, protocol information, or other identifiers. NeTraMet runs on DOS and most UNIX systems, including Linux and BSD.

Throughput testing
How fast can the network go? What is the actual usable capacity of a particular network link? You can get a very good estimate of your throughput capacity by flooding the link with traffic and measuring how long it takes to transfer the data.

Tools such as this one from SpeedTest.net are pretty, but don't always give you an accurate picture of network performance

While there are web pages available that will perform a speed test in your browser (such as http://www.dslreports.com/stest or http://speedtest.net/), these tests are increasingly inaccurate as you get further from the testing source. Even worse, they do not allow you to test the speed of a given link, but only the speed of your link to a particular site on the Internet. Here are a few tools that will allow you to perform throughput testing on your own networks.

Ttcp http://ftp.arl.mil/ftp/pub/ttcp/. Now a standard part of most Unix-like systems, ttcp is a simple network performance testing tool. One instance is run on either side of the link you want to test. The first node runs in receive mode, and the other transmits: node_a$ ttcp -r -s node_b$ ttcp -t -s node_a ttcp-t: buflen=8192, nbuf=2048, align=16384/0, port=5001 tcp -> node_a ttcp-t: socket ttcp-t: connect ttcp-t: 16777216 bytes in 249.14 real seconds = 65.76 KB/sec +++ ttcp-t: 2048 I/O calls, msec/call = 124.57, calls/sec = 8.22 ttcp-t: 0.0user 0.2sys 4:09real 0% 0i+0d 0maxrss 0+0pf 7533+0csw After collecting data in one direction, you should reverse the transmit and receive partners to test the link in the other direction. It can test UDP as well as TCP streams, and can alter various TCP parameters and buffer lengths to give the network a good workout. It can even use a usersupplied data stream instead of sending random data. Remember that the speed readout is in kilobytes, not kilobits. Multiply the result by 8 to find the speed in kilobits per second. The only real disadvantage to ttcp is that it hasnt been developed in years. Fortunately, the code has been released in the public domain and is freely available. Like ping and traceroute, ttcp is found as a standard tool on many systems.

Iperf http://dast.nlanr.net/Projects/Iperf/. Much like ttcp, iperf is a commandline tool for estimating the throughput of a network connection. It supports manyof the same features as ttcp, but uses a client and server model instead of a receive and transmit pair. To run iperf, launch a server on one side and a client on the other:

node_a$ iperf -s node_b$ iperf -c node_a -----------------------------------------------------------Client connecting to node_a, TCP port 5001 TCP window size: 16.0 KByte (default) -----------------------------------------------------------[ 5] local 10.15.6.1 port 1212 connected with 10.15.6.23 port 5001 [ ID] Interval Transfer Bandwidth [ 5] 0.0-11.3 sec 768 KBytes 558 Kbits/sec The server side will continue to listen and accept client connections on port 5001 until you hit control-C to kill it. This can make it handy when running multiple test runs from a variety of locations. The biggest difference between ttcp and iperf is that iperf is under active development, and has many new features (including IPv6 support). This makes it a good choice as a performance tool when building new networks.

Bing http://fgouget.free.fr/bing/index-en.shtml. Rather than flood a connection with data and see how long the transfer takes to complete, Bing attempts to estimate the available throughput of a pointto-point connection by analyzing round trip times for various sized ICMP packets. While it is not always as accurate as a flood test, it can provide a good estimate without transmitting a large number of bytes. Since bing works using standard ICMP echo requests, so it can estimate available bandwidth without the need to run a special client on the other end,and can even attempt to estimate the throughput of links outside your network. Since it uses relatively little bandwidth, bing can give you a rough idea of network performance without running up the charges that a flood test would certainly incur.

Realtime tools It is desirable to find out when people are trying to break into your network, or when some part of the network has failed. Because no system administrator can be monitoring a network all the time, there are programs that constantly monitor the status of the network and can send alerts when notable events occur. The following are some open source tools that can help perform this task.

Snort Snort (http://www.snort.org/) is a packet sniffer and logger which can be used as a lightweight network intrusion detection system. It features rulebased logging and can perform protocol analysis, content searching, and packet matching. It can be used to detect a variety of attacks and probes, such as stealth port scans, CGI attacks, SMB probes, OS fingerprinting attempts, and many other kinds of anomalous traffic patterns. Snort has a realtime alert capability that can notify administrators about problems as they occur with a variety of methods. Installing and running Snort is not trivial, and depending on the amount of network traffic, will likely require a dedicated monitoring machine with considerable resources. Fortunately, Snort is very well documented and has a strong user community. By implementing a comprehensive Snort rule set, you can identify unexpected behavior that would otherwise mysteriously eat up your Internet bandwidth. See http://snort.org/docs/ for an extensive list of installation and configuration resources.

Apache: mod_security ModSecurity (http://www.modsecurity.org/) is an open source intrusion detection and prevention engine for web applications. This kind of security tool is also known as a web application firewall. ModSecurity increases web application security by protecting web applications from known and unknown attacks. It can be used on its own, or as a module in the Apache web server (http://www.apache.org/). There are several sources for updated mod_security rules that help protect against the latest security exploits. One excellent resource is GotRoot, which maintains a huge and frequently updated repository of rules: http://gotroot.com/tiki-index.php?page=mod_security+rules Web application security is important in defending against attacks on your web server, which could result in the theft of valuable or personal data, or in the server being used to launch attacks or send spam to other Internet users. As well as being damaging to the Internet as a whole, such intrusions can seriously reduce your available bandwidth.

Nagios Nagios (http://nagios.org/) is a program that monitors hosts and services on your network, notifying you immediately when problems arise. It can send notifications via email, SMS, or by running a script, and will send notifications to the relevant person or group depending on the nature of the problem. Nagios runs on Linux or BSD, and provides a web interface to show up to the minute system status. Nagios is extensible, and can monitor the status of virtually any network event. It performs checks by running small scripts at regular intervals, and checks the results against an expected response. This can yield much more sophisticated checks than a simple network probe. For example, ping) may tell you that a machine is up, and nmap may report that a TCP port responds to requests, but Nagios can actually retrieve a web page or make a database request, and verify that the response is not an error.

Nagios keeps you informed the moment a network fault or service outage occurs.

Nagios can even notify you when bandwidth usage, packet loss, machine room temperature, or other network health indicator crosses a particular threshold. This can give you advance warning of network problems, often allowing you to respond to the problem before users have a chance to complain.

Zabbix Zabbix (http://www.zabbix.org/) is an open source realtime monitoring tool that is something of a hybrid between Cacti and Nagios. It uses a SQL database for data storage, has its own graph rendering package, and performs all of the functions you would expect from a modern realtime monitor (such as SNMP polling and instant notification of error conditions). Zabbix is released under the GNU General Public License.

Other useful tools There are thousands of free network monitoring tools that fill very specialized needs. Here are a few of our favorites that don't quite fit into the above categories. Driftnet and Etherpeg. These tools decode graphical data (such as GIF and JPEG files) and display them as a collage. As mentioned earlier, tools such as these are of limited use in troubleshooting problems, but are very valuable for demonstrating the insecurity of unencrypted protocols. Etherpeg is available from http://www.etherpeg.org/, and Driftnet can be downloaded at http://www.exparrot.com/~chris/driftnet/.

A web collage generated by Etherpeg

Ngrep Ngrep provides most of GNU grep's pattern matching features, but applies them to network traffic. It currently recognizes IPv4 and IPv6, TCP, UDP, ICMP, IGMP, PPP, SLIP, FDDI, Token Ring, and much more. As it makes extensive use of regular expression matches, it is a tool suited to advanced users or those that have a good knowledge of regular expressions. But you don't necessarily need to be a regex expert to be able to make basic use of ngrep. For example, to view all packets that contain the string GET (presumably HTTP requests), try this:

# ngrep -q GET Pattern matches can be constrained further to match particular protocols, ports, or other criteria using BPF filters. This is the filter language used by common packet sniffing tools, such as tcpdump and snoop. To view GET or POST strings sent to destination port 80, use this command line: # ngrep -q 'GET|POST' port 80 By using ngrep creatively, you can detect anything from virus activity to spam email. You can download ngrep at http://ngrep.sourceforge.net/.

What is normal? If you are looking for a definitive answer as to what your traffic patterns should look like, you are going to be disappointed. There is no absolute right answer to this question, but given some work you can determine what is normal for your network. While every environment is different, some of the factors that can influence the appearance of your traffic patterns are: The capacity of your Internet connection The number of users that have access to the network The social policy (byte charging, quotas, honor system, etc.). The number, types, and level of services offered The health of the network (presence of viruses, excessive broadcasts, routing loops, open email relays, denial of service attacks, etc.). The competence of your computer users The location and configuration of control structures (firewalls, proxy servers, caches, and so on) This is not a definitive list, but should give you an idea of how a wide range of factors can affect your bandwidth patterns. With this in mind, let's look at the topic of baselines.

Establishing a baseline Since every environment is different, you need to determine for yourself what your traffic patterns look like under normal situations. This is useful because it allows you to identify changes over time, either sudden or gradual. These changes may in turn indicate a problem, or a potential future problem, with your network. For example, suppose that your network grinds to a halt, and you are not sure of the cause. Fortunately, you have decided to keep a graph of broadcasts as a percentage of the overall network traffic. If this graph shows a sudden increase in the amount of broadcast traffic, it may mean that your network has been infected with a virus. Without an idea of what is "normal" for your network (a baseline), you would not be able to see that the number of broadcasts had increased, only that it was relatively high, which may not indicate a problem. Baseline graphs and figures are also useful when analyzing the effects of changes made to the network. It is often very useful to experiment with such changes by trying different possible

values. Knowing what the baseline looks like will show you whether your changes have improved matters, or made them worse.

By collecting data over a long period of time, you can predict the growth of your network and make changes before problems develop. In Figure above, we can see the effect the implementation of delay pools has made on Internet utilization around the period of May. If we did not keep a graph of the line utilization, we would never know what the effect of the change over the long term was. When watching a total traffic graph after making changes, don't assume that just because the graph does not change radically that your efforts were wasted. You might have removed frivolous usage from your line only to have it replaced by genuine legitimate traffic. You could then combine this baseline with others, say the top 100 sites accessed or the average utilization by your top twenty users, to determine if habits have simply changed. As we will see later, MRTG, RRDtool, and Cacti are excellent tools you can use to keep a baseline.

The traffic trend at Aidworld logged over a single day. Figure above shows traffic on an Aidworld firewall over a period of 24 hours. There is nothing apparently wrong with this graph, but users were complaining about slow Internet access. And Figure below shows that the upload bandwidth use (dark area) was higher during working hours on the last day than on previous days. A period of heavy upload usage started every morning at 03:00, and was normally fin ished by 09:00, but on the last day it was still running at 16:30. Further investigation revealed a problem with the backup software, which ran at 03:00 every day.

The same network logged over an entire week reveals a problem with backups, which caused unexpected congestion for network users. Figure below shows measurements of latency on the same connection as measured by a program called SmokePing. The position of the dots shows the average latency, while the gray smoke indicates the distribution of latency (jitter). The color of the dots indicates the number of lost packets. This graph over a period of four hours does not help to identify whether there are any problems on the network.

Four hours of jitter and packet loss.

The next graph shows the same data over a period of 16 hours. This indicates that the values in the graph above are close to the normal level (baseline), but that there were significant increases in latency at several times during the early morning, up to 30 times the baseline value. This indicates that additional monitoring should be performed during these early morning periods to establish the cause of the high latency, which is probably heavy traffic of some kind.

A higher spread of jitter is revealed in the 16 hour log.

The next Figure shows that Tuesday was significantly worse than Sunday or Monday for latency, especially during the early morning period. This might indicate that something has changed on the network.

Zooming out to the week long view reveals a definite repetition of increased latency and packet loss in the early morning hours.

How do I interpret the traffic graph? In a basic network flow graph (such as that generated by the network monitor MRTG), the green area indicates inbound traffic, while the blue line indicates outbound traffic. Inbound traffic is traffic that originates from another network (typically the Internet) and is addressed to a

computer inside your network. Outbound traffic is traffic that originates from your network, and is addressed to a computer somewhere on the Internet. Depending on what sort of network environment you have, the graph will help you understand how your network is actually being used. For example, monitoring of servers usually reveals larger amounts of outbound traffic as the servers respond to requests (such as sending mail or serving web pages), while monitoring cli ent machines might reveal higher amounts of inbound traffic to the machines as they receive data from the servers.

The classic network flow graph. The dark area represents inbound traffic, while the line represents outbound traffic. The repeating arcs of outbound traffic show when the nightly backups have run. Traffic patterns will vary with what you are monitoring. A router will normally show more incoming traffic than outgoing traffic as users download data from the Internet. An excess of outbound bandwidth that is not transmitted by your network servers may indicate a peer-to-peer client, unauthorized server, or even a virus on one or more of your clients. There are no set metrics that indicate what outgoing traffic to incoming traffic should look like. It is up to you to establish a baseline to understand what normal network traffic patterns look like on your network.

Detecting network overload Figure below shows traffic on an overloaded Internet connection.

Flat-topped graphs indicate that a line is using the maximum available bandwidth, and is overutilized during these times. The most apparent sign of overloading is the flat tops on outbound traffic during the middle of every day. Flat tops may indicate overloading, even if they are well below the maximum theoretical capacity of the link. In this case it may indicate that you are not getting as much bandwidth from your service provider as you expect. Measuring 95th percentile The 95th percentile is a widely used mathematical calculation to evaluate regular and sustained utilization of a network pipe. Its value shows the highest consumption of traffic for a given period. Calculating the 95th percentile means that 95% of the time the usage is below a certain amount, and 5% of the time usage is above that amount. The 95th percentile is a good value to use to show the bandwidth that is actually used at least 95% of the time.

The horizontal line shows the 95th percentile amount MRTG and Cacti will calculate the 95th Percentile for you. This is a sample graph of a 960 kbps connection. The 95th percentile came to 945 kbps after discarding the highest 5% of traffic.

Monitoring RAM and CPU usage By definition, servers provide critical services that should always be available. Servers receive and respond to client machine requests, providing access to services that are the whole point of having a network in the first place. Therefore, servers must have sufficient hardware capabilities to accommodate the work load. This means they must have adequate RAM, storage, and processing power to accommodate the number of client requests. Otherwise, the server will take longer to respond, or in the worst case, may be incapable of responding at all. Since hardware resources are finite, it is important to keep track of how system resources are being used. If a core server (such as a proxy server or email server) is overwhelmed by requests, access times become slow. This is often perceived by users as a network problem. There are several programs that can be used to monitor resources on a server. The simplest method on a Windows machine is to access the Task Manager using the Ctrl Alt + Del keys, and then click on the Performance tab. On a Linux or BSD box, you can type top in a terminal window. To keep historical logs of such performance, MRTG or RRDtool can also be used.

RRDtool can show arbitrary data, such as memory and CPU usage, expressed as an average over time. Mail servers require adequate space, as some people may prefer to leave their email messages on the server for long periods of time. The messages can accumulate and fill the hard disk, especially if quotas are not in use. If the disk or partition used for mail storage fills up, the mail server cannot receive mail. If that disk is also used by the system, all kinds of system problems may occur as the operating system runs out of swap space and temporary storage. File servers need to be monitored, even if they have large disks. Users will find a way to fill any size disk more quickly than you might think. Disk usage can be enforced through the use of quotas, or by simply monitoring usage and telling people when they are using too much. Nagios can notify you when disk usage, CPU utilization, or other system resources cross a critical threshold. If a machine becomes unresponsive or slow, and measurements show that a system resource is being heavily used, this may be an indication that an upgrade is required. If processor usage constantly exceeds 60% of the total, it may be time to upgrade the processor. Slow speeds could also be as a result of insufficient RAM. Be sure to check the overall usage of CPU, RAM, and disk space before deciding to upgrade a particular component.

A simple way to check whether a machine has insufficient RAM is to look at the hard disk light. When the light is on constantly, it usually means that the machine is constantly swapping large amounts of data to and from the disk. This is known as thrashing, and is extremely bad for performance. It can usually be fixed by investigating which process is using the most RAM, and killing or reconfiguring that process. Failing that, the system needs more RAM. You should always determine whether it is more cost effective to upgrade an individual component or purchase a whole new machine. Some computers are difficult or impossible to upgrade, and it often costs more to replace individual components than to replace the entire system. Since the availability of parts and systems varies widely around the world, be sure to weigh the cost of parts vs. whole systems, including shipping and taxes, when determining the cost of upgrading.

Solar Power
Here we provide an introduction to the components of a standalone photovoltaic system. The word standalone refers to the fact that the system works without any connection to an established power grid. Here, we will present the basic concepts of the generation and storage of hotovoltaic solar energy. We will also provide a method for designing a functional olar system with limited access to information and resources. Now we only discusse the use of solar energy for the direct production of electricity (photovoltaic solar energy). Solar energy can also be used to heat fluids (thermal solar energy) which can then be used as a heat source or to turn a turbine to generate electricity.

Solar energy A photovoltaic system is based on the ability of certain materials to convert the radiant energy of the sun into electrical energy. The total amount of solar energy that lights a given area is known as irradiance (G) and it is measured in watts per square meter (W/m2). The instantaneous values are normally averaged over a period of time, so it is common to talk about total irradiance per hour, day or month. Of course, the precise amount of radiation that arrives at the surface of the Earth cannot be predicted with high precision, due to natural weather variations. Therefore it is necessary to work with statistical data based on the "solar history" of a particular place. This data is gathered by a weather station over a long period and is available from a number of sources, as tables or databases. In most cases, it can be difficult to find detailed information about a specific area, and you will need to work with approximate values. A few organizations have produced maps that include average values of daily global irradiation for different regions. These values are known as peak sun hours or PSHs. You can use the PSH value for your region to simplify your calculations. One unit of "peak sun" corresponds to a radiation of 1000 Watts per square meter. If we find that certain area has 4 PSH in the worst of the months, it means that in that month we should not expect a daily irradiation bigger than 4000 W/m2 (day). The peak sun hours are an easy way to represent the worst case average of irradiation per day. Low resolution PSH maps are available from a number of online sources, such as http://www.solar4power.com/solar-power-global-maps.html . For more detailed information, consult a local solar energy vendor or weather station. What about wind power? It is possible to use a wind generator in place of solar panels when an autonomous system is being designed for installation on a hill or mountain. To be effective, the average wind speed over the year should be at least 3 to 4 meter per second, and the wind generator should be 6 meters higher than

other objects within a distance of 100 meters. A location far away from the coast usually lacks sufficient wind energy to support a wind powered system. Generally speaking, photovoltaic systems are more reliable than wind generators, as sunlight is more available than consistent wind in most places. On the other hand, wind generators are able to charge batteries even at night, as long as there is sufficient wind. It is of course possible to use wind in conjunction with solar power to help cover times when there is extended cloud cover, or when there is insufficient wind. For most locations, the cost of a good wind generator is not justified by the meager amount of power it will add to the overall system. This chapter will therefore focus on the use of solar panels for generating electricity.

Photovoltaic system components A basic photovoltaic system consists of four main components: the solar panel, the batteries, the regulator, and the load. The panels are responsible for collecting the energy of the sun and generating electricity. The battery stores the electrical energy for later use. The regulator ensures that panel and battery are working together in an optimal fashion. The load refers to any device that requires electrical power, and is the sum of the consumption of all lectrical equipment connected to the system. It is important to remember that solar panels and batteries use direct current (DC). If the range of operational voltage of your equipment does not fit the voltage supplied by your battery, it will also be necessary to include some type of converter. If the equipment that you want to power uses a different DC voltage than the one supplied by the battery, you will need to use a DC/DC converter. If some of your equipment requires AC power, you will need to use a DC/AC converter, also known as an inverter. Every electrical system should also incorporate various safety devices in the event that something goes wrong. These devices include proper wiring, circuit breakers, surge protectors, fuses, ground rods, lighting arrestors, etc.

The solar panel The solar panel is composed of solar cells that collect solar radiation and transform it into electrical energy. This part of the system is sometimes referred to as a solar module or photovoltaic generator. Solar panel arrays can be made by connecting a set of panels in series and/or parallel in order to provide the necessary energy for a given load. The electrical current supplied by a solar panel varies proportionally to the solar radiation. This will vary according to climatological conditions, the hour of the day, and the time of the year.

A solar panel Several technologies are used in the manufacturing of solar cells. The most common is crystalline silicon, and can be either monocrystalline or polycrystalline. Amorphous silicon can be cheaper but is less efficient at converting solar energy to electricity. With a reduced life expectancy and a 6 to 8% transformation efficiency, amorphous silicon is typically used for low power equipment, such as portable calculators. New solar technologies, such as silicon ribbon and thin film photovoltaics, are currently under development. These technologies promise higher efficiencies but are not yet widely available. The battery The battery stores the energy produced by the panels that is not immediately consumed by the load. This stored energy can then be used during periods of low solar irradiation. The battery component is also sometimes called the accumulator. Batteries store electricity in the form of chemical energy. The most common type of batteries used in solar applications are maintenance-free lead-acid batteries, also called recombinant or VRLA (valve regulated lead acid) batteries.

A 200 Ah lead-acid battery. The negative terminal was broken due to weight on the terminals during transportation. Aside from storing energy, sealed lead-acid batteries also serve two important functions: They are able to provide an instantaneous power superior to what the array of panels can generate. This instantaneous power is needed to start some appliances, such as the motor of a refrigerator or a pump. They determine the operating voltage of your installation. For a small power installation and where space constraints are important, other type of batteries (such as NiCd, NiMh, or Li-ion) can be used. These types of batteries need a specialized charger/regulator and cannot directly replace lead-acid batteries.

The regulator The regulator (or more formally, the solar power charge regulator) assures that the battery is working in appropriate conditions. It avoids overcharging or overdischarging the battery, both of which are very detrimental to the life of the battery. To ensure proper charging and discharging of the battery, the regulator maintains knowledge of the state of charge (SoC) of the battery. The SoC is estimated based on the actual voltage of the battery. By measuring the battery voltage and being programmed with the type of storage technology used by the battery, the regulator can know the precise points where the battery would be overcharged or excessively discharged.

A 30 Amp solar charge controller The regulator can include other features that add valuable information and security control to the equipment. These features include ammeters, voltmeters, measurement of ampere-hour, timers, alarms, etc. While convenient, none of these features are required for a working photovoltaic system.

The converter The electricity provided by the panel array and battery is DC at a fixed voltage. The voltage provided might not match what is required by your load. A direct/alternating (DC/AC) converter, also known as inverter, converts the DC current from your batteries into AC. This comes at the price of losing some energy during the conversion. If necessary, you can also use converters to obtain DC at voltage level other than what is supplied by the batteries. DC/DC converters also lose some energy during the conversion. For optimal operation, you should design your solar-powered system to match the generated DC voltage to match the load.

An 800 Watt DC/AC converter (power inverter) The load The load is the equipment that consumes the power generated by your energy system. The load may include wireless communications equipment, routers, workstations, lamps, TV sets, VSAT modems, etc. Although it is not possible to precisely calculate the exact total consumption of your equipment, it is vital to be able to make a good estimate. In this type of system it is absolutely necessary to use efficient and low power equipment to avoid wasting energy.

Putting it all together The complete photovoltaic system incorporates all of these components. The solar panels generate power when solar energy is available. The regulator ensures the most efficient operation of the panels and prevents damage to the batteries. The battery bank stores collected energy for later use. Converters and inverters adapt the stored energy to match the requirements of your load. Finally, the load consumes the stored energy to do work. When all of the components are in balance and are properly maintained, the system will support itself for years.

A solar installation with DC and AC loads We will now examine each of the individual components of the photovoltaic system in greater detail

The solar panel An individual solar panel is made of many solar cells. The cells are electrically connected to provide a particular value of current and voltage. The individual cells are properly encapsulated to provide isolation and protection from humidity and corrosion.

The effect of water and corrosion in a solar panel There are different types of modules available on the market, depending on the power demands of your application. The most common modules are composed of 32 or 36 solar cells of crystalline silicon. These cells are all of equal size, wired in series, and encapsulated between glass and plastic material, using a polymer resin (EVA) as a thermal insulator. The surface area

of the module is typically between 0.1 and 0.5 m2. Solar panels usually have two electrical contacts, one positive and one negative. Some panels also include extra contacts to allow the installation of bypass diodes across individual cells. Bypass diodes protect the panel against a phenomenon known as hot-spots. A hot-spot occurs when some of the cells are in shadow while the rest of the panel is in full sun. Rather than producing energy, shaded cells behave as a load that dissipates energy. In this situation, shaded cells can see a significant increase in temperature (about 85 to 100C.) Bypass diodes will prevent hot-spots on shaded cells, but reduce the maximum voltage of the panel. They should only be used when shading is unavoidable. It is a much better solution to expose the entire panel to full sun whenever possible.

Different IV Curves. The current (A) changes with the irradiance, and the voltage (V) changes with the temperature.

The electrical performance of a solar module its represented by the IV characteristic curve, which represents the current that is provided based on the voltage generated for a certain solar radiation. The curve represents all the possible values of voltage-current. The curves depend on two main factors: the temperature and the solar radiation received by the cells. For a given solar cell area, the current generated is directly proportional to solar irradiance (G), while the voltage reduces slightly with an increase of temperature. A good regulator will try to maximize the amount of energy that a panel provides by tracking the point that provides maximum power (V x I). The maximum power corresponds to the knee of the IV curve.

Solar Panel Parameters The main parameters that characterize a photovoltaic panel are: 1. SHORT CIRCUIT CURRENT (ISC): the maximum current provided by the panel when the connectors are short circuited. 2. OPEN CIRCUIT VOLTAGE (VOC): the maximum voltage that the panel provides when the terminals are not connected to any load (an open circuit). This value is normally 22 V for panels that are going to work in 12 V systems, and is directly proportional to the number of cells connected in series. 3. MAXIMUM POWER POINT (P max): the point where the power supplied by the panel is at maximum, where Pmax = Imax x Vmax. The maximum power point of a panel is measured in Watts (W) or peak Watts (Wp). It is important not to forget that in normal conditions the panel will not work at peak conditions, as the voltage of operation is fixed by the load or the regulator. Typical values of Vmax and Imax should be a bit smaller than the ISC and VOC 4. FILL FACTOR (FF): the relation between the maximum power that the panel can actually provide and the product ISC . VOC. This gives you an idea of the quality of the panel because it is an indication of the type of IV characteristic curve. The closer FF is to 1, the more power a panel can provide. Common values usually are between 0.7 and 0.8. 5. EFFICIENCY (h): the ratio between the maximum electrical power that the panel can give to the load and the power of the solar radiation (PL) incident on the panel. This is normally around 10-12%, depending on the type of cells (monocrystalline, polycrystalline, amorphous or thin film). Considering the definitions of point of maximum power and the fill factor we see that:

h = Pmax / PL = FF . ISC . VOC / PL The values of ISC , VOC, IPmax and VPmax are provided by the manufacturer and refer to standard conditions of measurement with irradiance G = 1000 W/m2, at sea-level, for a temperature of cells of Tc = 25C. The panel parameters values change for other conditions of irradiance and temperature. Manufacturers will sometimes include graphs or tables with values for conditions different from the standard. You should check the performance values at the panel temperatures that are likely to match your particular installation. Be aware that two panels can have the same Wp but very different behavior in different operating conditions. When acquiring a panel, it is important to verify, if possible, that their parameters (at least, ISC and VOC) match the values promised by the manufacturer.

Panel parameters for system sizing To calculate the number of panels required to cover a given load, you just need to know the current and voltage at the point of maximum power: IPmax and VPmax. You should always be aware that the panel is not going to perform under perfect conditions as the load or regulation system is not always going to work at the point of maximum power of the panel. You should assume a loss of efficiency of 5% in your calculations to compensate for this.

Interconnection of panels A solar panel array is a collection of solar panels that are electrically interconnected and installed on some type of support structure. Using a solar panel array allows you to generate greater voltage and current than is possible with a single solar panel. The panels are interconnected in such a way that the voltage generated is close to (but greater than) the level of voltage of the batteries, and that the current generated is sufficient to feed the equipment and to charge the batteries. Connecting solar panels in series increases the generated voltage. Connecting panels in parallel increases the current. The number of panels used should be increased until the amount of power generated slightly exceeds the demands of your load. It is very important that all of the panels in your array are as identical as possible. In an array, you should use panels of the same brand and characteristics because any difference in their operating conditions will have a big impact on the health and performance of your system. Even panels that have identical performance ratings will usually display some variance in their characteristics due to manufacturing processes. The actual operating characteristics of two panels from the same manufacturer can vary by as much as 10%. Whenever possible, it is a good idea to test the real-world performance of individual panels to verify their operating characteristics before assembling them into an array.

Interconnection of panels in parallel. The voltage remains constant while the current duplicates. (Photo: Fantsuam Foundation, Nigeria)

How to choose a good panel One obvious metric to use when shopping for solar panels is to compare the ratio of the nominal peak power (Wp) to the price. This will give you a rough idea of the cost per Watt for different panels. But there are a number of other considerations to keep in mind as well. If you are going to install solar panels in geographical areas where soiling (from dust, sand, or grit) will likely be a problem, consider purchasing panels with a low affinity for soil retention. These panels are made of materials that increase the likelihood that the panel will be automatically cleaned by wind and rain. Always check the mechanical construction of each panel. Verify that the glass is hardened and the aluminum frame is robust and well built. The solar cells inside the panel can last for more than 20 years, but they are very fragile and the panel must protect them from mechanical hazards. Look for the manufacturer's quality guarantee in terms of expected power output and mechanical construction. Finally, be sure that the manufacturer provides not only the nominal peak power of the panel (Wp) but also the variation of the power with irradiation and temperature. This is particularly important when panels are used in arrays, as variations in the operating parameters can have a big impact on the quality of power generated and the useful lifetime of the panels.

The battery The battery hosts a certain reversible chemical reaction that stores electrical energy that can later be retrieved when needed. Electrical energy is transformed into chemical energy when the battery is being charged, and the reverse happens when the battery is discharged. A battery is formed by a set of elements or cells arranged in series. Leadacid batteries consist of two submerged lead electrodes in an electrolytic solution of water and sulfuric acid. A potential difference of about 2 volts takes place between the electrodes, depending on the instantaneous value of the charge state of the battery. The most common batteries in photovoltaic solar applications have a nominal voltage of 12 or 24 volts. A 12 V battery therefore contains 6 cells in series. The battery serves two important purposes in a photovoltaic system: to provide electrical energy to the system when energy is not supplied by the array of solar panels, and to store excess energy generated by the panels whenever that energy exceeds the load. The battery experiences a cyclical process of charging and discharging, depending on the presence or absence of sunlight. During the hours that there is sun, the array of panels produces electrical energy. The energy that is not consumed immediately it is used to charge the battery. During the hours of absence of sun, any demand of electrical energy is supplied by the battery, thereby discharging it. These cycles of charge and discharge occur whenever the energy produced by the panels does not match the energy required to support the load. When there is sufficient sun and the load is light, the batteries will charge. Obviously, the batteries will discharge at night whenever any amount of power is required. The batteries will also discharge when the irradiance is insufficient to cover the requirements of the load (due to the natural variation of climatological conditions, clouds, dust, etc.) If the battery does not store enough energy to meet the demand during periods without sun, the system will be exhausted and will be unavailable for consumption. On the other hand, the oversizing the system (by adding far too many panels and batteries) is expensive and inefficient. When designing a stand-alone system we need to reach a compromise between the cost of components and the availability of power from the system. One way to do this is to estimate the required number of days of autonomy. In the case of a telecommunications system, the number of days of autonomy depends on its critical function within your network design. If the equipment is going to serve as repeater and is part of the backbone of your network, you will likely want to design your photovoltaic system with an autonomy of up to 5-7 days. On the other hand, if the solar system is responsible for a providing energy to client equipment you can probably reduce number of days of autonomy to two or three. In areas with low irradiance, this value may need to be increased even more. In any case, you will always have to find the proper balance between cost and reliability.

Types of batteries Many different battery technologies exist, and are intended for use in a variety of different applications. The most suitable type for photovoltaic applications is the stationary battery, designed to have a fixed location and for scenarios where the power consumption is more or less irregular. "Stationary" batteries can accommodate deep discharge cycles, but they are not designed to produce high currents in brief periods of time. Stationary batteries can use an electrolyte that is alkaline (such as Nickel- Cadmium) or acidic (such as Lead-Acid). Stationary batteries based on Nickel-Cadmium are recommended for their high reliability and resistance whenever possible. Unfortunately, they tend to be much more expensive and difficult to obtain than sealed lead-acid batteries. In many cases when it is difficult to find local, good and cheap stationary batteries (importing batteries is not cheap), you will be forced to use batteries targeted to the automobile market.

Using car batteries Automobile batteries are not well suited for photovoltaic applications as they are designed to provide a substantial current for just few seconds (when starting then engine) rather than sustaining a low current for long period of time. This design characteristic of car batteries (also called traction batteries) results in an shortened effective life when used in photovoltaic systems. Traction batteries can be used in small applications where low cost is the most important consideration, or when other batteries are not available. Traction batteries are designed for vehicles and electric wheelbarrows. They are cheaper than stationary batteries and can serve in a photovoltaic installation, although they require very frequent maintenance. These batteries should never be deeply discharged, because doing so will greatly reduce their ability to hold a charge. A truck battery should not discharged by more than 70% of its total capacity. This means that you can only use a maximum of 30% of a lead-acid battery's nominal capacity before it must be recharged. You can extend the life of a lead-acid battery by using distilled water. By using a densimeter or hydrometer, you can measure the density of the battery's electrolyte. A typical battery has specific gravity of 1.28. Adding distilled water and lowering the density to 1.2 can help reduce the anode's corrosion, at a cost of reducing the overall capacity of the battery. If you adjust the density of battery electrolyte, you must use distilled water, as tap water or well water will permanently damage the battery.

States of charge There are two special state of charge that can take place during the cyclic charge and discharge of the battery. They should both be avoided in order to preserve the useful life of the battery.

Overcharge Overcharge takes place when the battery arrives at the limit of its capacity. If energy is applied to a battery beyond its point of maximum charge, the electrolyte begins to break down. This produces bubbles of oxygen and hydrogen, in a process is known as gasification. This results in a loss of water, oxidation on the positive electrode, and in extreme cases, a danger of explosion. On the other hand, the presence of gas avoids the stratification of the acid. After several continuous cycles of charge and discharge, the acid tends to concentrate itself at the bottom of the battery thereby reducing the effective capacity. The process of gasification agitates the electrolyte and avoids stratification. Again, it is necessary to find a compromise between the advantages (avoiding electrolyte stratification) and the disadvantages (losing water and production of hydrogen). One solution is to allow a slight overcharge condition every so often. One typical method is to allow a voltage of 2.35 to 2.4 Volts for each element of the battery every few days, at 25C. The regulator should ensure a periodical and controlled overcharges.

Overdischarge
In the same way that there is a upper limit, there is also a lower limit to a battery's state of charge. Discharging beyond that limit will result in deterioration of the battery. When the effective battery supply is exhausted, the regulator prevents any more energy from being extracted from the battery. When the voltage of the battery reaches the minimum limit of 1.85 Volts per cell at 25C, the regulator disconnects the load from the battery. If the discharge of the battery is very deep and the battery remains discharged for a long time, three effects take place: the formation of crystallized sulfate on the battery plates, the loosening of the active material on the battery plate, and plate buckling. The process of forming stable sulfate crystals is called hard sulfation. This is particularly negative as it generates big crystals that do not take part in any chemical reaction and can make your battery unusable.

Battery Parameters The main parameters that characterize a battery are: Nominal Voltage, VNBat. the most common value being 12 V. Nominal Capacity, CNBat: the maximum amount of energy that can be extracted from a fully charged battery. It is expressed in Ampere-hours (Ah) or Watt-hours (Wh). The amount of energy that can be obtained from a battery depends on the time in which the extraction process takes place. Discharging a battery over a long period will yield more energy compared to discharging the same battery over a short period. The capacity of a battery is therefore specified at different

discharging times. For photovoltaic applications, this time should be longer than 100 hours (C100). Maximum Depth of Discharge, DoDmax: The depth of discharge is the amount of energy extracted from a battery in a single discharge cycle, expressed as a percentage. The life expectancy of a battery depends on how deeply it is discharged in each cycle. The manufacturer should provide graphs that relate the number of charge-discharge cycles to the life of the battery. As a general rule you should avoid discharging a deep cycle battery beyond 50%. Traction batteries should only be discharged by as little as 30%. Useful Capacity, CUBat: It is the real (as in usable) capacity of a battery. It is equal to the product of the nominal capacity and the maximum DoD. For example, a stationary battery of nominal capacity (C100) of 120 Ah and depth of discharge of 70% has a useful capacity of (120 x 0.7) 84 Ah.

Measuring the state of charge of the battery A sealed lead-acid battery of 12 V provides different voltages depending on its state of charge. When the battery is fully charged in an open circuit, the output voltage is about 12.8 V. The output voltage lowers quickly to 12.6 V when loads are attached. As the battery is providing constant current during operation, the battery voltage reduces linearly from 12.6 to 11.6 V depending on the state of charge. A sealed lead-acid batteries provides 95% of its energy within this voltage range. If we make the broad assumption that a fully loaded battery has a voltage of 12.6 V when "full" and 11.6 V when "empty", we can estimate that a battery has discharged 70% when it reaches a voltage of 11.9 V. These values are only a rough approximation since they depend on the life and quality of the battery, the temperature, etc. State of Charge 100% 90% 80% 70% 60% 50% 40% 30% 20% 10% 0% 12V BatteryVoltage 12,7 12,5 12,42 12,32 12,2 12,06 11,9 11,75 11,58 11,31 10,5 Volts per Cell 2,12 2,08 2,07 2,05 2,03 2,01 1,98 1,96 1,93 1,89 1,75

According to this table, and considering that a truck battery should not be discharged more than 20% to 30%, we can determine that the useful capacity of a truck 170 Ah truck battery is 34 Ah (20%) to 51 Ah (30%). Using the same table, we find that we should program the regulator to prevent the battery from discharging below 12.3 V.

Battery and regulator protection Thermomagnetic circuit breakers or one time fuses must be used to protect the batteries and the installation from short circuit and malfunctions. There are two types of fuses: slow blow, and quick blow. Slow blow fuses should be used with inductive or capacitive loads where a high current can occur at power up. Slow blow fuses will allow a higher current than their rating to pass for a short time. Quick blow fuses will immediately blow if the current flowing through them is higher than their rating. The regulator is connected to the battery and the loads, so two different kinds of protection needs to be considered. One fuse should be placed between the battery and the regulator, to protect the battery from short-circuit in case of regulator failure. A second fuse is needed to protect the regulator from excessive load current. This second fuse is normally integrated into the regulator itself.

A battery bank of 3600 Ah, currents reach levels of 45 A during charging Every fuse is rated with a maximum current and a maximum usable voltage. The maximum current of the fuse should be 20% bigger than the maximum current expected. Even if the batteries carry a low voltage, a short circuit can lead to a very high current which can easily reach several hundred amperes. Large currents can cause fire, damage the equipment and batteries, and possibly cause electric shock to a human body if a fuse breaks, never replace a fuse with a wire or a higher rated fuse. First determine the cause of the problem, and then replace the fuse with another one which has the same characteristics.

Temperature effects The ambient temperature has several important effects on the characteristics of a battery: The nominal capacity of a battery (that the manufacturer usually gives for 25C) increases with temperature at the rate of about 1%/C. But if the temperature is too high, the chemical reaction that takes place in the battery accelerates, which can cause the same type of oxidation that takes places during overcharging. This will obviously reduce the life expectancy of battery. This problem can be compensated partially in car batteries by using a low density of dissolution (a specific gravity of 1.25 when the battery is totally charged). As the temperature is reduced, the useful life of the battery increases. But if the temperature is too low, you run the the risk of freezing the electrolyte. The freezing temperature depends on the density of the solution, which is also related to the state of charge of the battery. The lower the density, the greater the risk of freezing. In areas of low temperatures, you should avoid deeply discharging the batteries (that is, DoDmax is effectively reduced.) The temperature also changes the relation between voltage and charge. It is preferable to use a regulator which adjusts the low voltage disconnect and reconnect parameters according to temperature. The temperature sensor of the regulator should be fixed to the battery using tape or some other simple method. In hot areas it is important to keep the batteries as cool as possible. The batteries must be stored in a shaded area and never get direct sunlight. It's also desirable to place the batteries on a small support to allow air to flow under them, thus increase the cooling.

How to choose a good battery Choosing a good battery can be very challenging in developing regions. High capacity batteries are heavy, bulky and expensive to import. A 200 Ah battery weights around 50 kg (120 pounds) and it can not be transported as hand luggage. If you want long-life (as in > 5 years) and maintenance free batteries be ready to pay the price. A good battery should always come with its technical specifications, including the capacity at different discharge rates (C20, C100), operating temperature, cut-off voltage points, and requirements for chargers. The batteries must be free of cracks, liquid spillage or any sign of damage, and battery terminals should be free of corrosion. As laboratory tests are necessary to obtain complete data about real capacity and aging, expect lots of low quality batteries (including fakes) in the local markets. A typical price (not including transport and import tax) is $3-4 USD per Ah for 12 V lead-acid batteries.

Life expectancy versus number of cycles Batteries are the only component of a solar system that should be amortized over a short period and regularly replaced. You can increase the useful lifetime of a battery by reducing the depth of discharge per cycle. Even deep cycle batteries will have an increased battery life if the the number of deep discharge (>30%) cycles is reduced. If you completely discharge the battery every day, you will typically need to change it after less than one year. If you use only 1/3 of the capacity the battery, it can last more than 3 years. It can be cheaper to buy a battery with 3 times the capacity than to change the battery every year.

The power charge regulator The power charge regulator is also known as charge controller, voltage regulator, chargedischarge controller or charge-discharge and load controller. The regulator sits between the array of panels, the batteries, and your equipment or loads. Remember that the voltage of a battery, although always close to 2 V per cell, varies according to its state of charge. By monitoring the voltage of the battery, the regulator prevents overcharging or overdischarging. Regulators used in solar applications should be connected in series: they disconnect the array of panels from the battery to avoid overcharging, and they disconnect the battery from the load to avoid overdischarging. The connection and disconnection is done by means of switches which can be of two types: electromechanical (relays) or solid state (bipolar transistor, MOSFET). Regulators should never be connected in parallel. In order to protect the battery from gasification, the switch opens the charging circuit when the voltage in the battery reaches its high voltage disconnect (HVD) or cut-off set point. The low voltage disconnect (LVD) prevents the battery from overdischarging by disconnecting or shedding the load. To prevent continuous connections and disconnections the regulator will not connect back the loads until the battery reaches a low reconnect voltage (LRV).

Typical values for a 12 V lead-acid battery are: Voltage Point LVD LRV Constant Voltage Regulated Equalization HVD Voltage 11,5 12,6 14,3 14,6 15,5

The most modern regulators are also able to automatically disconnect the panels during the night to avoid discharging of the battery. They can also periodically overcharge the battery to improve their life, and they may use a mechanism known as pulse width modulation (PWM) to prevent excessive gassing. As the peak power operating point of the array of panels will vary with temperature and solar illumination, new regulators are capable of constantly tracking the maximum point of power of the solar array. This feature is known as maximum power point tracking (MPPT).

Regulator Parameters When selecting a regulator for your system, you should at least know the operating voltage and the maximum current that the regulator can handle. The operating Voltage will be 12, 24, or 48 V. The maximum current must be 20% bigger than the current provided by the array of panels connected to the regulator. Other features and data of interest include: Specific values for LVD, LRV and HVD. Support for temperature compensation. The voltage that indicates the state of charge of the battery vary with temperature. For that reason some regulators are able to measure the battery temperature and correct the different cut-off and reconnection values. Instrumentation and gauges. The most common instruments measure the voltage of the panels and batteries, the state of charge (SoC) or Depth of Discharge (DoD). Some regulators include special alarms to indicate that the panels or loads have been disconnected, LVD or HVD has been reached, etc.

Converters The regulator provides DC power at a specific voltage. Converters and inverters are used to adjust the voltage to match the requirements of your load.

DC/DC Converters DC/DC converters transform a continuous voltage to another continuous voltage of a different value. There are two conversion methods which can be used to adapt the voltage from the batteries: linear conversion and switching conversion. Linear conversion lowers the voltage from the batteries by converting excess energy to heat. This method is very simple but is obviously inefficient. Switching conversion generally uses a magnetic component to temporarily store the energy and transform it to another voltage. The resulting voltage can be greater, less than, or the inverse (negative) of the input voltage. The efficiency of a linear regulator decreases as the difference between the input voltage and the

output voltage increases. For example, if we want to convert from 12 V to 6 V, the linear regulator will have an efficiency of only 50%. A standard switching regulator has an efficiency of at least 80%.

DC/AC Converter or Inverter Inverters are used when your equipment requires AC power. Inverters chop and invert the DC current to generate a square wave that is later filtered to approximate a sine wave and eliminate undesired harmonics. Very few inverters actually supply a pure sine wave as output. Most models available on the market produce what is known as "modified sine wave", as their voltage output is not a pure sinusoid. When it comes to efficiency, modified sine wave inverters perform better than pure sinusoidal inverters. Be aware that not all the equipment will accept a modified sine wave as voltage input. Most commonly, some laser printers will not work with a modified sine wave inverter. Motors will work, but they may consume more power than if they are fed with a pure sine wave. In addition, DC power supplies tend to warm up more, and audio amplifiers can emit a buzzing sound. Aside from the type of waveform, some important features of inverters include: Reliability in the presence of surges. Inverters have two power ratings: one for continuous power, and a higher rating for peak power. They are capable of providing the peak power for a very short amount of time, as when starting a motor. The inverter should also be able to safely interrupt itself (with a circuit breaker or fuse) in the event of a short circuit, or if the requested power is too high. Conversion efficiency. Inverters are most efficient when providing 50% to 90% of their continuous power rating. You should select an inverter that most closely matches your load requirements. The manufacturer usually provides the performance of the inverter at 70% of its nominal power. Battery charging. Many inverters also incorporate the inverse function: the possibility of charging batteries in the presence of an alternative source of current (grid, generator, etc). This type of inverter is known as a charger/ inverter. Automatic fall-over. Some inverters can switch automatically between different sources of power (grid, generator, solar) depending on what is available. When using telecommunication equipment, it is best to avoid the use of DC/ AC converters and feed them directly from a DC source. Most communications equipment can accept a wide range of input voltage.

Equipment or load It should be obvious that as power requirements increase, the expense of the photovoltaic system also increases. It is therefore critical to match the size of the system as closely as possible to the expected load. When designing the system you must first make a realistic estimate of the maximum consumption. Once the installation is in place, the established maximum consumption must be respected in order to avoid frequent power failures.

Home Appliances The use of photovoltaic solar energy is not recommended for heat-exchange applications (electrical heating, refrigerators, toasters, etc.) Whenever possible, energy should be used sparingly using low power appliances. Here are some points to keep in mind when choosing appropriate equipment for use with a solar system: The photovoltaic solar energy is suitable for illumination. In this case, the use of halogen light bulbs or fluorescent lamps is mandatory. Although these lamps are more expensive, they have much better energy efficiency than incandescent light bulbs. LED lamps are also a good choice as they are very efficient and are fed with DC. It is possible to use photovoltaic power for appliances that require low and constant consumption (as in a typical case, the TV). Smaller televisions use less power than larger televisions. Also consider that a black-and-white TV consumes about half the power of a color TV. Photovoltaic solar energy is not recommended for any application that transforms energy into heat (thermal energy). Use solar heating or butane as alternative. Conventional automatic washing machines will work, but you should avoid the use of any washing programs that include centrifuged water heating. If you must use a refrigerators, it should consume as little power as possible. There are specialized refrigerators that work in DC, although their consumption can be quite high (around 1000 Wh/day). The estimation of total consumption is a fundamental step in sizing your solar system. Here is a table that gives you a general idea of the power consumption that you can expect from different appliances.

Equipment Consumption (Watt) Portable computer 30-50 Low power lamp 6-10 WRAP router (one radio) 4-10 VSAT modem 15-30 PC (without LCD) 20-30 PC (with LCD) 200-300 Network Switch (16 port) 6-8

Wireless telecommunications equipment Saving power by choosing the right gear saves a lot of money and trouble. For example, a long distance link doesn't necessarily need a strong amplifier that draws a lot of power. A Wi-Fi card with good receiver sensitivity and a Fresnel zone that is at least 60% clear will work better than an amplifier, and save power consumption as well. A well known saying of radio amateurs applies here, too: The best amplifier is a good antenna. Further measures to reduce power consumption include throttling the CPU speed, reducing transmit power to the minimum value that is necessary to provide a stable link, increasing the length of beacon intervals, and switching the system off during times it is not needed. Most autonomous solar systems work at 12 or 24 volts. Preferably, a wireless device that runs on DC voltage should be used, operating at the 12 Volts that most lead acid batteries provide. Transforming the voltage provided by the battery to AC or using a voltage at the input of the access point different from the voltage of the battery will cause unnecessary energy loss. A router or access point that accepts 8-20 Volts DC is perfect. Most cheap access points have a switched mode voltage regulator inside and will work through such a voltage range without modification or becoming hot (even if the device was shipped with a 5 or 12 Volt power supply). WARNING: Operating your access point with a power supply other than the one provided by your manufacturer will certainly void any warranty, and may cause damage to your equipment. While the following technique will typically work as described, remember that should you attempt it, you do so at your own risk. Open your access point and look near the DC input for two relatively big capacitors and an inductor (a ferrite toroid with copper wire wrapped around it). If they are present then the device has a switched mode input, and the maximum input voltage should be somewhat below the voltage printed on the capacitors. Usually the rating of these capacitors is 16 or 25 volts. Be aware that an unregulated power supply has a ripple and may feed a much higher voltage into your access point than the typical voltage printed on it may suggest. So, connecting an unregulated power supply with 24 Volts to a device with 25 Volt-capacitors is not a good idea. Of course, opening your device will void any existing warranty. Do not try to

operate an access point at higher voltage if it doesn't have a switched mode regulator. It will get hot, malfunction, or burn. Equipment based on traditional Intel x86 CPUs are power hungry in comparison with RISCbased architectures as ARM or MIPS. One of the boards with lowest power consumptions is the Soekris platform that uses an AMD ElanSC520 processor. Another alternative to AMD (ElanSC or Geode SC1100) is the use of equipment with MIPS processors. MIPS processors have a better performance than an AMD Geode at the price of consuming between 20-30% of more energy. The popular Linksys WRT54G runs at any voltage between 5 and 20 volts DC and draws about 6 Watts, but it has an Ethernet switch onboard. Having a switch is of course nice and handy - but it draws extra power. Linksys also offers a Wi-Fi access point called WAP54G that draws only 3 Watts and can run OpenWRT and Freifunk firmware. The 4G Systems Accesscube draws about 6 Watts when equipped with a single WiFi interface. If 802.11b is sufficient, mini-PCI cards with the Orinoco chipset perform very well while drawing a minimum amount of power.

Equipment Linksys WRT54G (BCM2050 radio) Linksys WAP54G

Consumption (Watts) 6

3 (BCM2050 radio) Orinoco WavePoint II ROR 15 (30mW radio) Soekris net4511 1.8 (no radio) PC Engines WRAP.1E-1 2.04 (no radio) Mikrotik Routerboard 532 2.3 (no radio) Inhand ELF3 1.53 (no radio) Senao 250mW radio Ubiquiti 400mW radio 3 6

The amount of power required by wireless equipment depends not only on the architecture but on the number of network interfaces, radios, type of memory/storage and traffic. As a general rule, a wireless board of low consumption consumes 2 to 3 W, and a 200 mW radio card consumes as much as 3 W. High power cards (such as the 400 mW Ubiquity) consume around 6 W. A repeating station with two radios can range between 8 and 10 W. Although the standard IEEE 802.11 incorporates a power saving mode (PS) mechanism, its benefit is not as good as you might hope. The main mechanism for energy saving is to allow stations to periodically put their wireless cards to "sleep" by means of a timing circuit. When the wireless card wakes up it verifies if a beacon exists, indicating pending traffic. The energy saving therefore only takes place in the client side, as the access point always needs to remain awake to send beacons and store traffic for the clients. Power saving mode may be incompatible between implementations from different manufacturers, which can cause unstable wireless connections. It is nearly always best to leave power saving mode disabled on all equipment, as the difficulties created will likely outweigh the meager amount of saved power.

Selecting the voltage Most low power stand-alone systems use 12 V battery power as that is the most common operational voltage in sealed lead-acid batteries. When designing a wireless communication system you need to take into consideration the most efficient voltage of operation of your equipment. While the input voltage can accept a wide range of values, you need to ensure that the overall power consumption of the system is minimal.

Wiring An important component of the installation is the wiring, as proper wiring will ensure efficient energy transfer. Some good practices that you should consider include: Use a screw to fasten the cable to the battery terminal. Loose connections will waste power. Spread Vaseline or mineral jelly on the battery terminals. Corroded connection has an increased resistance, resulting in loss. For low currents (<10 A) consider the use of Faston or Anderson powerpole connectors. For bigger currents, use metallic ring lugs. Wire size is normally given in American Wire Gauge (AWG). During your calculations you will need to convert between AWG and mm2 to estimate cable resistance. For example, an AWG #6 cable has a diameter of 4.11 mm and can handle up to 55 A. A conversion chart, including an estimate of resistance and current carrying capacity, is available in Appendix C.

Keep in mind that the current carrying capacity can also vary depending on the type of insulation and application. When in doubt, consult the manufacturer for more information.

Orientation of the panels Most of the energy coming from the sun arrives in straight line. The solar module will capture more energy if it is facing the sun, perpendicular to the straight line between the position of the installation and the sun. Of course, the sun's position is constantly changing relative to the earth, so we need to find an optimal position for our panels. The orientation of the panels is determined by two angles, the azimuth a and the inclination or elevation . The azimuth is the angle that measures the deviation with respect to the south in the northern hemisphere, and with respect to the north in the southern hemisphere. The inclination is the angle formed by the surface of the module and the horizontal plane.

Azimuth You should have the module turned towards the terrestrial equator (facing south in the northern hemisphere, and north in the southern) so that during the day the panel catches the greatest possible amount of radiation (a = 0). It is very important that no part of the panels are ever under shade! Study the elements that surround the panel array (trees, buildings, walls, other panels, etc.) to be sure that they will not cast a shadow on the panels at any time of the day or year. It is acceptable to turn the panels 20 towards the east or the west if needed (a = 20).

Inclination Once you have fixed the azimuth, the parameter that is key in our calculations is the inclination of the panel, which we will express as the angle beta (). The maximum height that the sun reaches every day will vary, with the maximum on the day of the summer solstice and the minimum on the winter solstice. Ideally, the panels should track this variation, but this is usually not possible for cost reasons. In installations with telecommunications equipment it is normal to install the panels at a fixed inclination. In most telecommunications scenarios the energy demands of the system are constant throughout the year. Providing for sufficient power during the "worst month" will work well for the rest of the year. The value of should maximize the ratio between the offer and the demand of energy. For installations with consistent (or nearly consistent) consumption throughout the year, it is preferable to optimize the installation to capture the maximum radiation during "the winter" months. You should use the absolute value of the latitude of the place (angle F) increased by 10 ( = |F| + 10 ). For installations with less consumptions during winter, the value of the latitude of the place can be used as the solar panel inclination. This way the system is optimized for the months of spring and autumn ( = |F|).

For installations that are only used during summer, you should use the absolute value of the latitude of the place (angle F) decreased by 10 ( = |F| - 10). The inclination of the panel should never be less than 15 to avoid the accumulation of dust and/or humidity on the panel. In areas where snow and ice occur, it is very important to protect the panels and to incline them an angle of 65 or greater. If there is a considerable increase in consumption during the summer, you might consider arranging for two fixed inclinations, one position for the months of summer and another for the months of winter. This would require special support structures and a regular schedule for changing the position of the panels.

How to size your photovoltaic system When choosing equipment to meet your power needs, you will need to determine the following, at a minimum: The number and type of solar panels required to capture enough solar energy to support your load. The minimum capacity of the battery. The battery will need to store enough energy to provide power at night and through days with little sun, and will determine your number of days of autonomy. The characteristics of all other components (the regulator, wiring, etc.) needed to support the amount of power generated and stored. System sizing calculations are important, because unless the system components are balanced, energy (and ultimately, money) is wasted. For example, if we install more solar panels to produce more energy, the batteries should have enough capacity to store the additional energy produced. If the bank of batteries is too small and the load is not using the energy as it is generated, then energy must be thrown away. A regulator of a smaller amperage than needed, or one single cable that is too small, can be a cause of failure (or even fire) and render the installation unusable. Never forget that the ability of the photovoltaic energy to produce and store electrical energy is limited. Accidentally leaving on a light bulb during the day can easily drain your reserves before nighttime, at which point no additional power will be available. The availability of "fuel" for photovoltaic systems (i.e. solar radiation) can be difficult to predict. In fact, it is never possible to be absolutely sure that a standalone system is going to be able to provide the necessary energy at any particular moment. Solar systems are designed for a certain consumption, and if the user exceeds the planned limits the provision of energy will fail. The design method that we propose consists of considering the energy requirements, and based on them to calculate a system that works for the maximum amount of time so it is as reliable as

possible. Of course, if more panels and batteries are installed, more energy will be able to be collected and stored. This increase of reliability will also have an increase in cost. In some photovoltaic installations (such as the provision of energy for telecommunications equipment on a network backbone) the reliability factor is more important that the cost. In a client installation, low cost is likely going to be a the most important factor. Finding a balance between cost and reliability is not a easy task, but whatever your situation, you should be able to determine what it is expected from your design choices, and at what price. The method we will use for sizing the system is known as the method of the worst month. We simply calculate the dimensions of the standalone system so it will work in the month in which the demand for energy is greatest with respect to the available solar energy. It is the worst month of the year, as this month with have the largest ratio of demanded energy to available energy. Using this method, reliability is taken into consideration by fixing the maximum number of days that the system can work without receiving solar radiation (that is, when all consumption is made solely at the expense of the energy stored in the battery.) This is known as the maximum number of days of autonomy (N), and can be thought of as the number of consecutive cloudy days when the panels do not collect any significant amount of energy. When choosing N, it is necessary to know the climatology of the place, as well as the economic and social relevance of the installation. Will it be used to illuminate houses, a hospital, a factory, for a radio link, or for some other application? Remember that as N increases, so does the investment in equipment and maintenance. It is also important to evaluate all possible logistical costs of equipment replacement. It is not the same to change a discharged battery from an installation in the middle of a city versus one at the top a telecommunication tower that is several hours or days of walking distance. Fixing the value of N it is not an easy task as there are many factors involved, and many of them cannot be evaluated easily. Your experience will play an important role in this part of the system sizing. One commonly used value for critical telecommunications equipment is N = 5, whereas for low cost client equipment it is possible to reduce the autonomy to N = 3.

Data to collect Latitude of the installation. Remember to use a positive sign in the northern hemisphere and negative in the south. Solar radiation data. For the method of the "worst month" it is enough to know just twelve values, one for every month. The twelve numbers are the monthly average values of daily global irradiation on horizontal plane (Gdm(0), in kWh/m2 per day). The monthly value is the sum of the values of global irradiation for every day of the month, divided by the number of days of the month. If you have the data in Joules (J), you can apply the following conversion: 1 J = 2.78 10 -7 kWh

The irradiation data Gdm(0) of many places of the world is gathered in tables and databases. You should check for this information from a weather station close to your implementation site, but do not be surprised if you cannot find the data in electronic format. It is a good idea to ask companies that install photovoltaic systems in the region, as their experience can be of great value. Do not confuse "sun hours" with the number of "peak sun hours". The number of peak sun hours has nothing to do with the number of hours without clouds, but refers to the amount of daily irradiation. A day of 5 hours of sun without clouds does not necessary have those hours when the sun is at its zenith. A peak sun hour is a normalized value of solar radiation of 1000 W/m2 at 25 C. So when we refer to 5 peak sun hours, this implies a daily solar radiation of 5000 W/m2.

Electrical characteristics of system components The electrical characteristics of the components of your system should be provided by the manufacturer. It is advisable to make your our own measurements to check for any deviation from the nominal values. Unfortunately, deviation from promised values can be large and should be expected. These are the minimum values that you need to gather before starting your system sizing: Panels You need to know the voltage VPmax and the current IPmax at the point of maximum power in standard conditions.

Batteries Nominal capacity (for 100 hours discharge) CNBat , operational voltage VNBat , and either the maximum depth of discharge DoDmax or useful capacity CUBat . You also need to know the type of battery that you plan to use, whether sealed lead-acid, gel, AGM, modified traction etc. The type of battery is important when deciding the cut-off points in the regulator.

Regulator You need to know the nominal voltage VNReg, and the maximum current that can operate ImaxReg. DC/AC Converter/Inverter If you are going to use a converter, you need to know the nominal voltage VNConv, instantaneous power PIConv and performance at 70% of maximum load H70. Equipment or load It is necessary to know the nominal voltage VNC and the nominal power of operation PC for every piece of equipment powered by the system. In order to know the total energy that our installation is going to consume, itis also very important to consider the average time each load will be used. Is it constant? Or will it be used daily, weekly, monthly or annually? Consider any changes in the usage that might impact the amount of energy needed (seasonal usage, training or school periods, etc.) Other variables Aside from the electrical characteristics of the components and load, it is necessary to decide on two more pieces of information before being able to size a photovoltaic system. These two decisions are the required number of days of autonomy and the operational voltage of the system. N, number of days of autonomy You need to decide on a value for N that will balance meteorological conditions with the type of installation and overall costs. It is impossible to give a concrete value of N that is valid for every installation, but the next table gives some recommended values. Take these values as a rough approximation, and consult with an experienced designer to reach a final decision. Available Sunlight Very cloudy Variable Sunny Domestic installation 5 4 3 Critical Installation 10 8 6

VN, nominal voltage of the installation The components of your system need to be chosen to operate at a nominal voltage VN. This voltage is usually 12 or 24 Volts for small systems, and if the total power of consumption surpasses 3 kW, the voltage will be 48 V. The selection of VN is not arbitrary, and depends on the availability of equipment. If the equipment allows it, try to fix the nominal voltage to 12 or 24 V. Many wireless communications boards accept a wide range of input voltage and can be used without a converter.

If you need to power several types of equipment that work at different nominal voltages, calculate the voltage that minimizes the overall power consumption including the losses for power conversion in DC/DC and DC/ AC converters.

Procedure of calculation There are three main steps that need to be followed to calculate the proper size of a system: 1. Calculate the available solar energy (the offer). Based on statistical data of solar radiation, and the orientation and the optimal inclination of the solar panels, we calculate the solar energy available. The estimation of solar energy available is done in monthly intervals, reducing the statistical data to 12 values. This estimation is a good compromise between precision and simplicity. 2. Estimate the required electrical energy (the demand). Record the power consumption characteristics of the equipment chosen as well as estimated usage. Then calculate the electrical energy required on a monthly basis. You should consider the expected fluctuations of usage due to the variations between winter and summer, the rainy period / dry season, school / vacation periods, etc. The result will be 12 values of energy demand, one for each month of the year. 3. Calculate the ideal system size (the result). With the data from the worst month, when the relation between the solar demanded energy and the energy available is greatest, we calculate: The current that the array of panels needs to provide, which will determine the minimum number of panels. The necessary energy storage capacity to cover the minimum number of days of autonomy, which will determine the required number of batteries. The required electrical characteristics of the regulator. The length and the necessary sections of cables for the electrical connections.

Required current in the worst month For each month you need to calculate the value of I m, which is the maximum daily current that an array of panels operating at nominal voltage of VN needs to provide, in a day with a irradiation of Gdm for month "m", for panels with an inclination of degrees.. The Im(WORST MONTH) will be the largest value of Im, and the system sizing is based on the data of that worth month. The calculations of Gdm() for a certain place can be made based on Gdm(0) using computer software such as PVSYST (http://www.pvsyst.com/) or PVSOL (http://www.solardesign.co.uk/).

Due to losses in the regulator and batteries, and due to the fact that the panels do not always work at the point of maximum power, the required current ImMAX is calculated as: ImMAX = 1.21 Im (WORST MONTH) Once you have determined the worst month, the value of ImMAX, and the total energy that you require ETOTAL(WORST MONTH) you can proceed to the final calculations. ETOTAL is the sum of all DC and AC loads, in Watts. To calculate ETOTAL.

Number of panels By combining solar panels in series and parallel, we can obtain the desired voltage and current. When panels are connected in series, the total voltage is equal to the sum of the individual voltages of each module, while the current remains unchanged. When connecting panels in parallel, the currents are summed together while the voltage remains unchanged. It is very important, to use panels of nearly identical characteristics when building an array. You should try to acquire panels with VPmax a bit bigger than the nominal voltage of the system (12, 24 or 48 V). Remember that you need to provide a few volts more than the nominal voltage of the battery in order to charge it. If it is not possible to find a single panel that satisfies your requirements, you need to connect several panels in series to reach your desired voltage. The number of panels in series Nps is equal to the nominal voltage of the system divided by the voltage of a single panel, rounded up to the nearest integer. Nps = VN / VPmax In order to calculate the number of panels in parallel (Npp), you need to divide the ImMAX by the current of a single panel at the point of maximum power Ipmax, rounded up to the nearest integer. Npp = ImMAX / IPmax The total number of panels is the result of multiplying the number of panels in series (to set the voltage) by the number of panels in parallel (to set the current). NTOTAL = Nps x Npp

Capacity of the battery or accumulator The battery determines the overall voltage of the system and needs to have enough capacity to provide energy to the load when there is not enough solar radiation. To estimate the capacity of our battery, we first calculate the required energy capacity of our system (necessary capacity, CNEC). The necessary capacitydepends on the energy available during the "worst month" and the desired number of days of autonomy (N). CNEC (Ah)= ETOTAL(WORST MONTH)(Wh) / VN (V) x N

The nominal capacity of the battery CNOM needs to be bigger than the CNEC as we cannot fully discharge a battery. To calculate the size of the battery we need to consider the maximum depth of discharge (DoD) that the battery allows: CNOM(Ah) = CNEC(Ah) / DoDMAX In order to calculate the number of batteries in series (Nbs), we divide the nominal voltage of our installation (VN) by the nominal voltage of a single battery (VNBat): Nbs = VN / VNBat

Regulator One important warning: always use regulators in series, never in parallel. If your regulator does not support the current required by your system, you will need to buy a new regulator with a larger working current. For security reasons, a regulator needs to be able to operate with a current ImaxReg at least 20% greater than the maximum intensity that is provided by the array of panels: ImaxReg = 1.2 Npp IPMax

DC/AC Inverter The total energy needed for the AC equipment is calculated including all the losses that are introduced by the DC/AC converter or inverter. When choosing an inverter, keep in mind that the performance of the inverter varies according to the amount of requested power. An inverter has better performance characteristics when operating close to its rated power. Using a 1500 Watt inverter to power a 25 Watt load is extremely inefficient. In order to avoid this wasted energy, it is important to consider not the peak power of all your equipment, but the peak power of the equipment that is expected to operate simultaneously.

Cables Once you know the numbers of panels and batteries, and type of regulators and inverters that you want to use, it is necessary to calculate the length and the thickness of the cables needed to connect the components together. The length depends on the location of your installation. You should try to minimize the length of the cables between the regulator, panels, and batteries. Using short cables will minimize lost power and cable costs. The thickness is chosen is based on the length of the cable and the maximum current it must carry. The goal is to minimize voltage drops. In order to calculate the thickness S of the cable it is necessary to know:

The maximum current IMC that is going to circulate in the cable. In the case of the panelbattery subsystem, it is ImMAX calculated for every month. In the battery-load subsystem it depends on the way that the loads are connected. The voltage drop (Va-Vb) that we consider acceptable in the cable. The voltage drop that results of adding all possible individual drops is expressed as a percent of the nominal voltage of the installation. Typical maximum values are: Voltage Drop (% of VN) Panel Array -> Battery 1% Battery -> Converter 1% Main Line 3% Main Line (Illumination) 3% Main Line (Equipment) 5% Component

Typical acceptable voltage drops in cables The section of the cable is determined by Ohm's Law: S(mm2) = r( mm2/m)L(m) ImMAX(A)/ (Va-Vb)(V) Where S is the section, r is resistivity (intrinsic property of the material: for copper, 0.01286 mm2/m), and L the length. S is chosen taking into consideration the cables available in the market. You should choose the immediately superior section to the one that is obtained from the formula. For security reasons that are some minimum values, for the cable that connects panels and battery, this is a minimum of 6 mm2. For the other sections, that minimum is 4 mm 2.

Cost of a solar installation While solar energy itself is free, the equipment needed to turn it into useful electric energy is not. You not only need to buy equipment to transform the solar energy in electricity and store it for use, but you must also replace and maintain various components of the system. The problem of equipment replacement is often overlooked, and a solar system is implemented without a proper maintenance plan. In order to calculate the real cost of your installation, we include an illustrative example. The first thing to do it is to calculate the initial investment costs.

Description Number Unit Cost Subtotal 60W Solar panel 4 $300 $1,200 (about $4 / W) 30A Regulator 1 $100 $100 Wiring (meters) 25 $1/ meter $25 50 Ah Deep cycle batteries 6 $150 $900 $2,225 Total The calculation of our investment cost is relatively easy once the system has been dimensioned. You just need to add the price for each piece equipment and the labor cost to install and wire the equipments together. For simplicity, we do not include the costs of transport and installation but you should not overlook them. To figure out how much a system will really cost to operate we must estimate how long each part will last and how often you must replace it. In accounting terminology this is known as amortization. Our new table will look like this: Description # Unit Cost Subtotal Lifetime (Years) $1,200 $100 $25 $900 $2,225 20 5 10 5 Biaya tahunan: Yearly Cost $60 $20 $2.50 $180 $262.50

60W Solar panel 4 $300 30A Regulator 1 $100 Wiring (meters)50 Ah 25 $1/ meter 50 Ah Deep 6 $150 cycle batteries Total:

As you see, once the first investment has been done, an annual cost of $262.50 is expected. The annual cost is an estimation of the required capital per year to replace the system components once they reach the end of their useful life.

Building an Outdoor Node


There are many practical considerations when installing electronic equipment outdoors. Obviously, it has to be protected from the rain, wind, sun, and other harsh elements. Power needs to be provided, and the antenna should be mounted at a sufficient height. Without proper grounding, nearby lightning strikes, fluctuating mains power, and even a light winds in the proper climate can annihilate your wireless links. This chapter will give you some idea of the practical problems you will be up against when installing wireless equipment outdoors.

Waterproof enclosures Suitable waterproof enclosures come in many varieties. Metal or plastic may be used to create a watertight container for outdoor embedded equipment. Of course, equipment needs power to work, and will likely need to connect to an antenna and Ethernet cable. Each time you pierce a watertight enclosure, you provide another potential place for water to seep in. The National Electrical Manufacturers Association (NEMA) provides guidelines for protection of electrical equipment from rain, ice, dust, and other contaminants. An enclosure with a rating of NEMA 3 or better is suitable for outdoor use in a fair climate. A NEMA 4X or NEMA 6 provides excellent protection, even from hose driven water and ice. For fixtures that pierce the body of an enclosure (such as cable glands and bulkhead connectors), the International Electrotechnical Commission (IEC) assigns an ingress protection (IP) rating. An ingress protection rating of IP66 or IP67 will protect these holes from very strong jets of water. A good outdoor enclosure should also provide UV protection to prevent breakdown of the seal from exposure to the sun, as well as to protect the equipment inside. Of course, finding NEMA or IEC rated enclosures may be a challenge in your local area. Often, locally available parts can be repurposed for use as enclosures. Rugged plastic or metal sprinkler boxes, electrical conduit housings, or even plastic food containers can be used in a pinch. When piercing an enclosure, use quality gaskets or o-rings along with a cable gland to seal the opening. UV stabilized silicone compound or other sealant can be used for temporary installations, but remember that cables flex in the wind, and glued joints will eventually weaken and allow moisture to seep in. You can greatly extend the life of a plastic enclosure by providing some protection from the sun. Mounting the box in the shade, either beneath existing equipment, solar panel, or thin sheet of metal specifically for this purpose, will add to the life span of the box as well as the equipment contained inside. Before putting any piece of electronics in a sealed box, be sure that it has minimal heat dissipation requirements. If your motherboard requires a fan or large heat sink, remember that there will be no airflow, and your electronics will likely bake to death on the tower. Only use electronic components that are designed to be used in an embedded environment.

Providing power Obviously, DC power can be provided by simply poking a hole in your enclosure and running a wire. If your enclosure is large enough (say, an outdoor electrical box) you could even wire an AC outlet inside the box. But manufacturers are increasingly supporting a very handy feature that eliminates the need for an additional hole in the box: Power over Ethernet (POE). The 802.3af standard defines a method for supplying power to devices using the unused pairs in a standard Ethernet cable. Nearly 13 Watts of power can be provided safely on a CAT5 cable without interfering with data transmissions on the same wire. Newer 802.3af compliant Ethernet switches (called end span injectors) supply power directly to connected devices. End span switches can supply power on the same wires that are used for data (pairs 1- 2 and 3-6) or on the unused wires (pairs 4-5 and 7-8). Other equipment, called mid span injectors, are inserted between Ethernet switches and the device to be powered. These injectors supply power on the unused pairs. If your wireless router or CPE includes support for 802.3af, you could in theory simply connect it to an injector. Unfortunately, some manufacturers (notably Cisco) disagree on power polarity, and connecting mismatching gear can damage the injector and the equipment to be powered. Read the fine print and be sure that your injector and wireless equipment agree on which pins and polarity should be used for power. If your wireless equipment doesnt support power over Ethernet, you can still use the unused pairs in a CAT5 cable to carry power. You can either use a passive POE injector, or simply build one yourself. These devices manually connect DC power to the unused wires on one end of the cable, and connect the other end directly to a barrel connector inserted in the devices power receptacle. A pair of passive POE devices can typically be purchased for under $20. To make your own, you will need to find out how much power the device requires to operate, and provide at least that much current and voltage, plus enough to account for loss in the Ethernet run. You dont want to supply too much power, as the resistance of the small cable can present a fire hazard. Here is an online calculator that will help you calculate the voltage drop for a given run of CAT5 : http://www.gweep.net/~sfoskett/tech/poecalc.html Once you know the proper power and electrical polarity needed to power your wireless gear, crimp a CAT5 cable only using the data wires (pairs 1-2 and 3-6). Then simply connect the transformer to pairs 4-5 (usually blue / bluewhite) and 7-8 (brown / brown-white) on one end, and a matching barrel connector on the other.

Mounting considerations In many cases, equipment can be located inside a building, provided there is a window with ordinary glass through which the beam can travel. Normal glass will introduce little attenuation, but tinted glass will introduce unacceptable attenuation. This greatly simplifies mounting, power, and weatherproofing problems, but is obviously only useful in populated areas. When mounting antennas on towers, it is very important to use a stand off bracket, and not mount the antennas directly to the tower. These brackets help with many functions including antenna separation, antenna alignment and protection. Stand off brackets need to be strong enough to support the weight of the antenna, and also hold it in place on windy days. Remember, antennas can actlike small sails, and can put a lot of force on to their mounts in strong winds. When estimating wind resistance, the total surface of the antenna structure must be considered, as well as the distance from the center of the antenna to the point of attachment to the building. Large antennas such as solid dishes or high gain sectorial panels can have considerable wind load. Using a slotted or mesh parabolic, rather than a solid dish, will help reduce the wind load without much affect on antenna gain. Be sure that the mounting brackets and supporting structure are solid, or your antennas will become misaligned over time (or worse, fall off the tower entirely!) Mounting brackets must have enough clearance from the tower to allow for aiming, but not too much clearance that the antennas become too hard to reach if any service or maintenance is required.

An antenna with a standoff bracket being lifted onto a tower. The pipe on the standoff bracket that the antenna will be mounted on needs to be round. This way the antenna can be pivoted on the pipe for aiming. Secondly, the pipe must also be vertical. If it is being mounted on a tapered tower, the standoff bracket will have to be designed to allow for this. This can be done using different lengths of steel, or by using combinations of threaded rod and steel plates.

As the equipment will be outside for all of its service life, it is important to be sure that the steel used is weatherproofed. Stainless steel often has too high a price tag for tower installations. Hot galvanizing is preferred, but may not be available in some areas. Painting all steel with a good rust paint will also work. If paint is chosen, it will be important to plan a yearly inspection of the mount and repaint when necessary.

Guyed towers A climbable guyed tower is an excellent choice for many installations, but for very tall structures a self supporting tower might be required. When installing guyed towers, a pulley attached to the top of a pole will facilitate the tower installation. The pole will be secured to the lower section already in place, while the two tower sections are attached with an articulated joint. A rope passing through the pulley will facilitate the raising of the next section. After the cantilever section becomes vertical, bolt it to the lower section of the pole. The pole (called a gin pole in the trade) can then be removed, and the operation may be repeated, if required. Tighten the guy wires carefully, ensuring that you use the same tension at all suitable anchoring points. Chose the points so that the angles, as seen from the center of the tower, are as evenly spaced as possible.

A climbable guyed tower

Self-supporting towers Self supporting towers are expensive but sometimes needed, particularly when greater elevation is a requirement. This can be as simple as a heavy pole sunk into a concrete piling, or as complicated as a professional radio tower.

A simple self-supporting tower An existing tower can sometimes be used for subscribers, although AM transmitting station antennas should be avoided because the whole structure is active. FM station antennas are acceptable, provided that at least a few of meters of separation is kept between the antennas. Be aware that while adjacent transmitting antennas may not interfere with your wireless connection, high powered FM may interfere with your wired Ethernet cable. Whenever using a heavily populated antenna tower, be very scrupulous about proper grounding and consider using shielded cable.

A much more complicated tower Rooftop assemblies Non-penetrating roof mount antenna assemblies can be used on flat roofs. These consist of a tripod mounted to a metal or wooden base. The base is then weighed down with bricks, sandbags, water jugs, or just about anything heavy. Using such a rooftop sled eliminates the need to pierce the roof with mounting bolts, avoiding potential leaks.

This metal base can be weighed down with sandbags, rocks, or water bottles to make a stable platform without penetrating a roof.

Wall mount or metal strap assemblies can be used on existing structures such as chimneys or the sides of a buildings. If the antennas have to be mounted more than about 4 meters above the rooftop, a climbable tower may be a better solution to allow easier access to the equipment and to prevent antenna movement during high winds.

Dissimilar metals To minimize electrolytic corrosion when two different metals are in moist contact, their electrolytic potential should be as close as possible. Use dielectric grease on the connection between two metals of different type to prevent any electrolysis effect. Copper should never touch galvanized material directly without proper joint protection. Water shedding from the copper contains ions that will wash away the galvanized (zinc) tower covering. Stainless steel can be used as a buffer material, but you should be aware that stainless steel is not a very good conductor. If it is used as a buffer between copper and galvanized metals, the surface area of the contact should be large and the stainless steel should be thin. Joint compound should also be used to cover the connection so water can not bridge between the dissimilar metals. Protecting microwave connectors Moisture leakage in connectors is likely the most observed cause of radio link failure. Be sure to tighten connectors firmly, but never use a wrench or other tool to do so. Remember that metals expand and contract as temperature changes, and an over-tightened connector can break in extreme weather changes.

A drip loop forces rainwater away from your connectors. Once tight, connectors should be protected by applying a layer of electrical tape, then a layer of sealing tape, and then another layer of electrical tape on top. The sealant protects the connector from water seepage, and the tape layer protects the sealant from ultraviolet (UV) damage. Cables should have an extra drip loop to prevent water from getting inside the transceiver.

Safety Always use a harness securely attached to the tower when working at heights. If you have never worked on a tower, hire a professional to do it for you. Many countries require special training for people to be allowed to work on towers above a certain height. Avoid working on towers during strong winds or storms. Always climb with a partner, and only when there is plenty of light. Tower work will likely take longer than you think it will. Remember that it is extremely hazardous to work in the dark. Give yourself plenty of time to complete the job long before the sun sets. If you run out of time, remember that the tower will be there in the morning, when you can start on the problem again after a good nights sleep.

Aligning antennas on a long distance link To properly align antennas at a great distance, you will need some sort of visual feedback that shows you the instantaneous received power at the antenna feed. This lets you to make small changes to the antenna alignment while watching the feedback tool, ultimately stopping when the maximum received power has been found. The ideal antenna alignment toolkit consists of a signal generator and a spectrum analyzer, preferably one of each at both ends of the link. By attaching a signal generator to one end of the link and a spectrum analyzer to the other, you can observe the received power and watch the effect of moving the antenna to various positions in real time. Once the maximum has been found on one end of a point to point link, the generator and analyzer can be swapped, and the process repeated for the other end. The use of a signal generator is preferable to using the radio card itself, as the signal generator can generate a continuous carrier. A WiFi card transmits many discrete packets of information, switching the transmitter on and off very rapidly. This can be very difficult to find with a spectrum analyzer, particularly when operating in noisy areas. Obviously, the cost of a calibrated signal generator and spectrum analyzer that works at 2.4 GHz (or even 5 GHz if using 802.11a) is well beyond the budget of most projects. Fortunately there are a number of inexpensive tools that can be used instead.

Inexpensive signal generator There are many inexpensive transmitters that use the 2.4 GHz ISM band. For example, cordless phones, baby monitors, and miniature television transmitters all generate a continuous signal at 2.4 GHz. Television transmitters (sometimes called video senders) are particularly useful, since they often include an external SMA antenna connector and can be powered by a small battery.

Video senders usually include support for three or four channels. While these do not directly correspond to WiFi channels, they permit you to test the low, middle, or high end of the band. For 5 GHz work, you can use a video sender in combination with a 2.4 GHz to 5 GHz converter. These devices accept a low power 2.4 GHz signal and emit high power 5 GHz signals. They are usually quite expensive ($300- $500 each) but will still likely be cheaper than a 5 GHz signal generator and spectrum analyzer.

A 2.4 GHz video sender with an SMA antenna connector Whatever you choose for a signal source, you will need a way to display the received power level levels at the other end. While the cost of 2.4 GHz spectrum analyzers is slowly coming down, they still typically cost a few thousand dollars, even for used equipment. Wi-Spy The Wi-Spy is a USB spectrum analysis tool made by MetaGeek (http://www.metageek.net/). It features a very sensitive receiver in a small form factor (about the size of a USB thumb drive).

The Wi-Spy USB spectrum analyzer The latest version of the Wi-Spy includes better dynamic range and an external antenna connector. It also comes with very good spectrum analysis software for Windows called Chanalyzer. It provides instantaneous, average, maximum, topographic, and spectral views.

The distinctive spiked pattern to the left of the graph was caused by a high power 2.4 GHz television transmitter. There is an excellent free software package for Mac OS X called EaKiu (http://www.cookwareinc.com/EaKiu/). In addition to the standard views, it also provides an animated 3D view, and adds support for multiple Wi-Spy devices.

EaKiu's 3D view lets you rotate and zoom in on any part of the graph in real time. There is probably a WiFi network on channel 11, with other noise sources lower down in the band. For Linux users, the Wi-Spy is supported by the Kismet Spectrum-Tools project (http://kismetwireless.net/spectools/). This package includes command line tools as well as a GUI built on GTK.

Other methods Some wireless routers (such as the Mikrotik) provide an "antenna alignment tool" that shows you a moving bar representing the received power. When the bar is at the maximum, the antenna is aligned. With some routers, you can also enable an audio feedback mode. This causes the router to emit a loud tone, changing the pitch according to the received power. If you don't have a spectrum analyzer, Wi-Spy, or a device that supports an antenna alignment mode, you will need to use the operating system to provide feedback about the wireless link quality. One simple method to do this in Linux is with a loop that continually calls iwconfig. For example: wildnet:~# while :; do clear; iwconfig; sleep 1; done

This will show the state of all radio cards in the system, updating once every second. Note that this will only work on the client end of a link. On the access point (master mode) side, you should use the iwspy command to collect statistics for the MAC address of the client: wildnet:~# iwspy ath0 00:15:6D:63:6C:3C wildnet:~# iwspy ath0 Statistics collected: 00:15:6D:63:6C:3C : Quality=21/94 Signal=-74 dBm Noise=-95 dBm Link/Cell/AP : Quality=19/94 Signal=-76 dBm Noise=-95 dBm Typical/Reference : Quality:0 Signal level:0 Noise level:0 You can then use a while loop (as in the previous example) to continually update the link status. wildnet:~# while :; do clear; iwspy; sleep 1; done

Antenna alignment procedure The key to successfully aligning antennas on a very long distance link is communication. If you change too many variables at once (say, one team starts wiggling an antenna while the other tries to take a signal strength reading), then the process will take all day and will probably end with misaligned antennas. You will have two teams of people. Ideally, each team should have at least two people: one to take signal readings and communicate with the remote end, the other to manipulate the antenna. Keep these points in mind while working on long distance links. 1. Test all equipment ahead of time. You dont want to fiddle with settings once youre in the field. Before separating the equipment, power everything on, connect every antenna and pigtail, and make sure you can establish a connection between the devices. You should be able to return to this known good state by simply powering on the device, without having to log in or change any settings. Now is a good time to agree on antenna polarization. 2. Bring backup communications gear. While mobile phones are usually good enough for working in cities, mobile reception can be bad or nonexistent in rural areas. Bring a high powered FRS or GMRS radio, or if your teams have amateur radio licenses, use a ham rig. Working at a distance can be very frustrating if you are constantly asking the other team can you hear me now? Pick your communication channels and test your radios (including the batteries) before separating. 3. Bring a camera. Take some time to document the location of each site, including surrounding landmarks and obstructions. This can be very useful later to determine the feasibility of another link to the location without having to travel there in person. If this is your first trip to the site, log the GPS coordinates and elevation as well. 4. Start by estimating the proper bearing and elevation. To begin, both teams should use triangulation (using GPS coordinates or a map) to get a rough idea of the direction to point. Use a compass to roughly align the antenna to the desired bearing. Large landmarks are also useful

for pointing. If you can use binoculars to see the other end, all the better. Once you have made your guess, take a signal strength reading. If you are close enough and have made a good guess, you may already have signal. 5. If all else fails, build your own landmark. Some kinds of terrain make it difficult to judge the location of the other end of a link. If you are building a link in an area with few landmarks, a self-made landmark such as a kite, balloon, flood light, flare, or even smoke signal might help. You dont necessarily need a GPS to get an idea of where to point your antenna. 6. Test signal in both directions, but only one at a time. Once both ends have made their best guess, the end with the lowest gain antenna should make fix their antenna into position. Using a good monitoring tool (such as Kismet, Netstumbler, or a good built-in wireless client), the team with the highest gain antenna should slowly sweep it horizontally while watching the signal meter. Once the best position is found, try altering the elevation of the antenna. After the best possible position is found, lock the antenna firmly into place and signal the other team to begin slowly sweeping around. Repeat this process a couple of times until the best possible position for both antennas is found. 7. Dont touch the antenna when taking a reading. Your body will affect the radiation pattern of the antenna. Do not touch the antenna, and dont stand in the path of the shot, when taking signal strength readings. The same goes for the team on the other side of the link, too. 8. Dont be afraid to push past the best received signal. As we saw in chapter four, radiation patterns incorporate many smaller sidelobes of sensitivity, in addition to a much larger main lobe. If your received signal is mysteriously small, you may have found a sidelobe. Continue sweeping slowly beyond that lobe to see if you can find the main lobe. 9. The antenna angle may look completely wrong. The main lobe of an antenna often radiates slightly to one side or the other of the visual dead center of the antenna. Offset feed dishes will seem to be pointing too far down, or even directly at the ground. Dont worry about how the antenna looks; you are concerned with finding the best possible position to achieve the greatest possible received signal. 10. Double-check polarization. It can be frustrating to attempt aligning a dish only to discover that the other team is using the opposite polarization. Again, this should be agreed upon before leaving home base, but if a link stays stubbornly weak, a double check doesnt hurt. 11. If nothing works, check all components one at a time. Are the devices on both ends of the link powered on? Are all pigtails and connectors properly connected, with no damaged or suspect parts? As outlined in chapter eight, proper troubleshooting technique will save you time and frustration. Work slowly and communicate your status well with the other team. By working methodically and communicating well, you can complete the job of aligning high gain antennas in just a short while. If done properly, it should be fun!

Surge and lightning protection Power is the greatest challenge for most installations in the developing world. Where there are electrical networks, they are often poorly controlled, fluctuate dramatically and are susceptible to lightning. Proper surge protection is critical to not only protect your wireless equipment, but all of the equipment connected to it.

Fuses and circuit breakers Fuses are critical, but very often neglected. In rural areas, and even in many urban areas of developing countries, fuses are difficult to find. Despite the added cost, it is always prudent to use circuit breakers instead. These may need to be imported, but shouldn't be overlooked. Too often, replaceable fuses are removed and pocket change is used instead. In a recent case, all of the electronic equipment at at rural radio station was destroyed when a lightning strike went through the circuit, without circuit breaker or even a fuse to protect it. How to ground Proper grounding doesnt have to be a complicated job. When grounding, you are trying to accomplish two things: provide a short-circuit for a lightning strike, and provide a circuit for excess energy to be dissipated. The first step is to protect equipment from a direct or near direct lightning hit, while the second provides a path to dissipate excess energy that would otherwise cause a build-up of static electricity. Static can cause significant degradation to signal quality, particularly on sensitive receivers (VSATs for example). Providing the short-circuit is simple. The installer simply needs to make the shortest path from the highest conductive surface (a lightning rod) to the ground. When a strike hits the rod, the energy will travel the shortest path and thus by-pass the equipment. This ground should be able to handle high-voltage (i.e. you need thick gauge wire, like 8 gauge braided copper). To ground the equipment, mount a lightning rod above the equipment on a tower or other structure. Then use a thick gauge conductive wire to connect the rod to something that itself is well grounded. Underground copper pipes can be very well grounded (depending on their depth, the moisture, salinity, amount of metal and organic content of the soil). In many sites in West Africa, pipes arent yet in the ground, and previous grounding equipment is often inadequate due to illconductive soil (typical of seasonally arid, tropical soils). There are three easy ways to measure the efficiency of your ground: 1. The least accurate is to simply plug a good quality UPS or power strip into the circuit that has a ground detect indicator (a LED light). This LED is lit by energy that is being diffused to the ground circuit. An effective ground will dissipate small amounts of energy to the ground. Some people actually use this to pirate a bit of free light, as this energy does not turn an electrical counter!

2. Take a light socket and a low-wattage bulb (30 Watts), connect one wire to the ground wire and the second to the hot wire. If the ground is working, the bulb should shine slightly. 3. The more sophisticated way is to simply measure the impedance between the positive circuit and the ground. If your ground is not efficient you will need to bury a grounding stake deeper (where the soil is more moist, has more organic matter and metals) or you need to make the ground more conductive. A common approach where there is little soil is to dig a hole that is 1 meter in diameter and 2 meters deep. Drop in a highly conductive piece of metal that has some mass to it. This is sometimes called a plomb, which literally means lead but can be any heavy piece of metal weighing 50 kg or more, such as an iron anvil or steel wheel. Then fill the hole with charcoal and mix in salt, then top with soil. Soak the area, and the charcoal and salt will diffuse around the hole and make a conductive area surrounding your plomb, improving the efficiency of the ground. If radio cable is being used, it too can be used to ground the tower, though a more resilient design is to separate the ground for the tower from the cable. To ground the cable, simply peel back a bit of cable at the point closest to the ground before it goes into the building, then attach a ground cable from that point, either by soldering or using a very conductive connector. This then needs to be waterproofed.

Power stabilizers & regulators There are many brands of power stabilizers, but most are either digital or electromechanical. The latter are much cheaper and more common. Electromechanicalstabilizers take power at 220V, 240V, or 110V and use that energy to turn a motor, which always produces the desired voltage (normally 220V). This is normally effective, but these units offer little protection from lightning or other heavy surges. They often burn out after just one strike. Once burnt, they can actually be fused at a certain (usually wrong) output voltage. Digital regulators regulate the energy using resistors and other solid state components. They are more expensive, but are much less susceptible to being burnt. Whenever possible, use a digital regulator. They are worth the added cost, and will offer better protection for the rest of your equipment. Be sure to inspect all components of your power system (including the stabilizer) after lightning activity.

Troubleshooting
How you establish the support infrastructure for your network is as important as what type of equipment you use. Unlike wired connections, problems with a wireless network are often invisible, and can require more skill and more time to diagnose and remedy. Interference, wind, and new physical obstructions can cause a long-running network to fail. This chapter details a series of strategies to help you build a team that can support your network effectively.

Building your team Every village, company or family has individuals who are intrigued by technology. They are the ones found splicing the television cable, re-wiring a broken television or welding a new piece to a bicycle. These people will take interest in your network and want to learn as much about it as possible. Though these people are invaluable resources, you must avoid imparting all of the specialized knowledge of wireless networking to only one person. If your only specialist loses interest or finds better paying work somewhere else, they take the knowledge with them when they go. There may also be many young and ambitious teenagers or young adults who will be interested and have the time to listen, help, and learn about the network. Again, they are very helpful and will learn quickly, but the project team must focus their attention on those who are best placed to support the network in the coming months and years. Young adults and teenagers will go off to university or find employment, especially the ambitious youth who tend to want to be involved. These youth also have little influence in the community, where an older individual is likely to be more capable of making decisions that positively affect the network as a whole. Even though these individuals might have less time to learn and might appear to be less interested, their involvement and proper education about the system can be critical. Therefore, a key strategy in building a support team is to balance and to distribute the knowledge among those who are best placed to support the network for the long term. You should involve the youth, but do not let them capitalize use or knowledge of these systems. Find people who are committed to the community, who have roots in the community, who can be motivated, and teach them. A complementary strategy is to compartmentalize functions and duties, and to document all methodology and procedures. In this way, people can be trained easily, and substituted with little effort. For example, in one project site the training team selected a bright young university graduate who had returned to his village. He was very motivated and learned quickly. Because he learned so quickly, he was taught more than had been foreseen, and he was able to deal with a variety of problems, from fixing a PC to rewiring Ethernet cable. Unfortunately, two months after the project launch he was offered a government job and left the community. Even a better salary could not keep him, since the prospect of a stable government job was too appealing. All of the knowledge about the network and how to support it left with him. The training team had to return

and begin the training again. The next strategy was to divide functions, and to train people who were permanently rooted in the community: People who had houses and children, and were already employed. It took three times as long to teach three people as it took to train the young university grad, but the community will retain this knowledge for much longer. Though this might seem to suggest that you should hand-pick who is to be involved, that is not often the best approach. It is often best to find a local partner organization or a local manager, and work with them to find the right technical team. Values, history, local politics, and many other factors will be important to them, while remaining completely unfathomable to people who are not from that community. The best approach is to coach your local partner, to provide them sound criteria, make sure that they understand that criteria, and to set firm boundaries. Such boundaries should include rules about nepotism and patronage, though these rules must consider the local situation. It may be impossible to say that you cannot hire kin, but it is best to provide a means of checks and balances. Where a candidate is kin, there should be clear criteria and a second authority in deciding upon their candidacy. It is also important that the local partner is given this authority and is not undermined by the project organizers, thus compromising their ability to manage. They will be best able to judge who will work best with them. If they are well educated in this process, then your requirements should be satisfied. Troubleshooting and support of technology is an abstract art. The first time you look at an abstract painting, it may just look to you like a bunch of random paint splatters. After reflecting on the composition for a time, you may come to appreciate the work as a whole, and the invisible coherence becomes very real. The neophyte looking at a wireless network may see the antennas and wires and computers, but it can take a while for them to appreciate the point of the invisible network. In rural areas, it can often take a huge leap of understanding before locals will appreciate an invisible network that is simply dropped into their village. Therefore, a phased approach is needed to ease people into supporting technology systems. The best method is involvement. Once the participants are chosen and committed to the project, involve them as much as possible. Let them "drive". Give them the cable crimper or keyboard and show them how to do the work. Even if you do not have time to explain every detail and even if it will take longer, they need to be involved physically and see not only what has been done, but how much work was done. The scientific method is taught in virtually all western schools. Many people learn about it by the time they reach high-school science class. Simply put, you take a set of variables, then slowly eliminate those variables through binary tests until you are left with one or only a few possibilities. With those possibilities in mind, you complete the experiment. You then test to see if the experiment yields something similar to the expected result. If it did not, you recalculate your expected result and try again. The typical agrarian villager may have been introduced to the concept, but likely will not have had the opportunity to troubleshoot complex problems. Even if they are familiar with the scientific method, they might not think to

apply it to resolving real problems. This method is very effective, although time consuming. It can be sped up by making logical assumptions. For example, if a long-running access point suddenly stops working after a storm, you might suspect a power supply related problem and thus skip most of the procedure. People charged with supporting technology should be taught how to troubleshoot using this method, as there will be times when the problem is neither known nor evident. Simple decision trees or flow charts can be made that test these variables, and try to eliminate the variables to isolate the problem. Of course, these charts should not be followed blindly. It is often easier to teach this method using a non technological problem first. For example, have your student develop a problem resolution procedure on something simple and familiar, like a battery powered television. Start by sabotaging the television. Give them a battery that is not charged. Disconnect the aerial. Insert a broken fuse. Test the student, making it clear that each problem will show specific symptoms, and point the way as to how to proceed. Once they have fixed the television, have them apply this procedure to a more complicated problem. In a network, you can change an IP address, switch or damage cables, use the wrong SSID, or orient the antenna in the wrong direction. It is important that they develop a methodology and procedure to resolve these problems.

Proper troubleshooting technique No troubleshooting methodology can completely cover all problems you will encounter when working with wireless networks. But often, problems come down to one of a few common mistakes. Here are a few simple points to keep in mind that can get your troubleshooting effort working in the right direction. Dont panic. If you are troubleshooting a system that means that it was working at one time, probably very recently. Before jumping in and making changes, survey the scene and assess exactly what is broken. If you have historical logs or statistics to work from, all the better. Be sure to collect information first, so you can make an informed decision before making changes. Is it plugged in? This step is often overlooked until many other avenues are explored. Plugs can be accidentally (or intentionally) unplugged very easily. Is the lead connected to a good power source? Is the other end connected to your device? Is the power light on? It may sound silly, but you will feel even sillier if you spend a lot of time checking out an antenna feed line only to realize that the AP was unplugged the entire time. Trust me, it happens more often than most of us would care to admit. What was the last thing changed? If you are the only person with access to the system, what is the last change you made? If others have access to it, what is the last change they made and when? When was the last time the system worked? Often, system changes have unintended consequences that may not be immediately noticed. Roll back that change and see what effect it has on the problem. Make a backup. This applies before you notice problems, as well as after. If you make a complicated software change to a system, having a backup means that you can quickly restore it

to the previous settings and start again. When troubleshooting very complex problems, having a configuration that sort-of works can be much better than having a mess that doesnt work at all (and that you cant easily restore from memory). The known good. This idea applies to hardware, as well as software. A known good is any component that you can replace in a complex system to verify that its counterpart is in good, working condition. For example, you may carry a tested Ethernet cable in a tool kit. If you suspect problems with a cable in the field, you can easily swap out the suspect cable with the known good and see if things improve. This is much faster and less errorprone than re-crimping a cable, and immediately tells you if the change fixes the problem. Likewise, you may also pack a backup battery, antenna cable, or a CD-ROM with a known good configuration for the system. When fixing complicated problems, saving your work at a given point lets you return to it as a known good, even if the problem is not yet completely solved. Change one variable at a time. When under pressure to get a failed system back online, it is tempting to jump ahead and change many likely variables at once. If you do, and your changes seem to fix the problem, then you will not understand exactly what led to the problem in the first place. Worse, your changes may fix the original problem, but lead to more unintended consequences that break other parts of the system. By changing your variables one at a time, you can precisely understand what went wrong in the first place, and be able to see the direct effects of the changes you make. Do no harm. If you dont fully understand how a system works, dont be afraid to call in an expert. If you are not sure if a particular change will damage another part of the system, then either find someone with more experience or devise a way to test your change without doing damage. Putting a penny in place of a fuse may solve the immediate problem, but it may also burn down the building. It is unlikely that the people who design your network will be on call twentyfour hours per day to fix problems when they arise. Your troubleshooting team will need to have good troubleshooting skills, but may not be competent enough to configure a router from scratch or crimp a piece of LMR-400. It is often much more efficient to have a number of backup components on-hand, and train your team to be able to swap out the entire broken part. This could mean having an access point or router pre-configured and sitting in a locked cabinet, plainly labeled and stored with backup cables and power supplies. Your team can swap out the failed component, and either send the broken part to an expert for repair, or arrange to have another backup sent in. Assuming that the backups are kept secure and are replaced when used, this can save a lot of time for everyone.

Common network problems Often, connectivity problems come from failed components, adverse weather, or simple misconfiguration. Once your network is connected to the Internet or opened up to the general public, considerable threats will come from the network users themselves. These threats can range from the benign to the outright malevolent, but all will have impact on your network if it is

not properly configured. This section looks at some common problems found once your network is used by actual human beings.

Locally hosted websites If a university hosts its website locally, visitors to the website from outside the campus and the rest of the world will compete with the university's staff for Internet bandwidth. This includes automated access from search engines that periodically spider your entire site. One solution to this problem is to use split DNS and mirroring. The university mirrors a copy of its websites to a server at, say, a European hosting company, and uses split DNS to direct all users from outside the university network to the mirror site, while users on the university network access the same site locally. Details about how to set this up are provided in chapter three.

In Example 1, all website traffic coming from the Internet must traversethe VSAT. In Example 2, the public web site is hosted on a fast European service, while a copy is kept on an internal server for very fast local access. This improves the VSAT connection and reduces load times for web site users.

Open proxies A proxy server should be configured to accept only connections from the university network, not from the rest of the Internet. This is because people elsewhere will connect and use open proxies for a variety of reasons, such as to avoid paying for international bandwidth. The way to configure this depends on the proxy server you are using. For example, you can specify the IP address range of the campus network in your squid.conf file as the only network that can use Squid. Alternatively, if your proxy server lies behind a border firewall, you can configure the firewall to only allow internal hosts to connect to the proxy port.

Open relay hosts An incorrectly configured mail server will be found by unscrupulous people on the Internet, and be used as a relay host to send bulk email and spam. They do this to hide the true source of the spam, and avoid getting caught. To test for an open relay host, the following test should be carried out on your mail server (or on the SMTP server that acts as a relay host on the perimeter of the campus network). Use telnet to open a connection to port 25 of the server in question (with some Windows versions of telnet, it may be necessary to type 'set local_echo' before the text is visible): telnet mail.uzz.ac.zz 25 Then, if an interactive command-line conversation can take place (for example, as follows), the server is an open relay host: MAIL FROM: spammer@waste.com 250 OK - mail from <spammer@waste.com> RCPT TO: innocent@university.ac.zz 250 OK - rcpt to spammer@waste.com Instead, the reply after the first MAIL FROM should be something like: 550 Relaying is prohibited. An online tester is available at sites such as http://www.ordb.org/. There is also information about the problem at this site. Since bulk emailers have automated methods to find such open relay hosts, an institution that does not protect its mail systems is almost guaranteed to be found and abused. Configuring the mail server not to be an open relay consists of specifying the networks and hosts that are allowed to relay mail through them in the MTA (eg., Sendmail, Postfix, Exim, or Exchange). This will likely be the IP address range of the campus network. Peer-to-peer networking Bandwidth abuse through peer-to-peer (P2P) file-sharing programs such as Kazaa, Morpheus, BitTorrent, WinMX and BearShare can be prevented in the following ways:

Make it impossible to install new programs on campus computers. By not giving regular users administrative access to PC workstations, it is possible to prevent the installation of programs such as Kazaa. Many institutions also standardize on a desktop build, where they install the required operating system on one PC. They then install all the necessary applications on it, and configure these in an optimal way. The PC is also configured in a way that prevents users from installing new applications. A disk image of this PC is then cloned to all other PCs using software such as Partition Image (see http://www.partimage.org/) or Drive Image Pro (see http://www.powerquest.com/). From time to time, users may succeed in installing new software or otherwise damaging the software on the computer (causing it to hang often, for example). When this happens, an administrator can simply put the disk image back, causing the operating system and all software on the computer to be exactly as specified. Blocking these protocols is not a solution. This is because Kazaa and other protocols are clever enough to bypass blocked ports. Kazaa defaults to port 1214 for the initial connection, but if that is not available it will attempt to use ports 1000 to 4000. If these are blocked, its uses port 80, making it look like web traffic. For this reason, ISPs don't block it but "throttle it", using bandwidth management tools. If rate-limiting is not an option, change the network layout. If the proxy server and mail servers are configured with two network cards (as described in chapter three) and these servers are not configured to forward any packets, this would block all P2P traffic. It would also block all other types of traffic, such as Microsoft NetMeeting, SSH, VPN software, and all other services not specifically permitted by the proxy server. In low bandwidth networks it may be decided that the simplicity of this design will outweigh the disadvantages. Such a decision may be necessary, but shouldnt be taken lightly. Network administrators simply cannot predict how users will make innovative use of a network. By preemptively blocking all access, you will prevent users from making use of any services (even low-bandwidth services) that your proxy does not support. While this may be desirable in extremely low bandwidth circumstances, it should never be considered as a good access policy in the general case.

Programs that install themselves (from the Internet) There are programs that automatically install themselves and then keep on using bandwidth - for example, the so-called Bonzi-Buddy, the Microsoft Network, and some kinds of worms. Some programs are spyware, which keep sending information about a user's browsing habits to a company somewhere on the Internet. These programs are preventable to some extent by user education and locking down PCs to prevent administrative access for normal users. In other cases, there are software solutions to find and remove these problem programs, such as Spychecker (http://www.spychecker.com/) or Ad-Aware (http://www.lavasoft.de/).

Windows updates The latest Microsoft Windows operating systems assume that a computer with a LAN connection has a good link to the Internet, and automatically downloads security patches, bug fixes and feature enhancements from theMicrosoft Web site. This can consume massive amounts of bandwidth on an expensive Internet link. The two possible approaches to this problem are: Disable Windows updates on all workstation PCs. The security updates are very important for servers, but whether workstations in a protected private network such as a campus network need them is debatable. Install a Software Update Server. This is a free program from Microsoft that enables you to download all the updates from Microsoft overnight on to a local server and distribute the updates to client workstations from there. In this way, Windows updates need not use any bandwidth on the Internet link during the day. Unfortunately, all client PCs need to be configured to use the Software Update Server for this to have an effect. If you have a flexible DNS server, you can also configure it to answer requests for indowsupdate.microsoft.com and direct the updater to your update server. This is only a good option for large networks, but can save untold amounts of Internet bandwidth. Blocking the Windows updates site on the proxy server is not a good solution because the Windows update service (Automatic Updates) keeps retrying more aggressively, and if all workstations do that, it places a heavy load on the proxy server. The extract below is from the proxy log (Squid access log) where this was done by blocking Microsoft's cabinet (.cab) files. Much of the Squid log looks like this: 2003.4.2 13:24:17 192.168.1.21 http://windowsupdate.microsoft.com/ident.cab *DENIED* Banned extension .cab GET 0 2003.4.2 13:24:18 192.168.1.21 http://windowsupdate.microsoft.com/ident.cab *DENIED* Banned extension .cab GET 0 2003.4.2 13:24:18 192.168.1.21 http://windowsupdate.microsoft.com/ident.cab *DENIED* Banned extension .cab HEAD 0 2003.4.2 13:24:19 192.168.1.21 http://windowsupdate.microsoft.com/ident.cab *DENIED* Banned extension .cab GET 0 2003.4.2 13:24:19 192.168.1.21 http://windowsupdate.microsoft.com/ident.cab *DENIED* Banned extension .cab GET 0 2003.4.2 13:24:20 192.168.1.21 http://windowsupdate.microsoft.com/ident.cab *DENIED* Banned extension .cab GET 0 2003.4.2 13:24:21 192.168.1.21 http://windowsupdate.microsoft.com/ident.cab *DENIED* Banned extension .cab GET 0 2003.4.2 13:24:21 192.168.1.21 http://windowsupdate.microsoft.com/ident.cab *DENIED* Banned extension .cab GET 0 2003.4.2 13:24:21 192.168.1.21 http://windowsupdate.microsoft.com/ident.cab *DENIED* Banned extension .cab HEAD 0

While this may be tolerable for a few PC clients, the problem grows significantly as hosts are added to the network. Rather than forcing the proxy server to serve requests that will always fail, it makes more sense to redirect the Software Update clients to a local update server.

Programs that assume a high bandwidth link In addition to Windows updates, many other programs and services assume that bandwidth is not a problem, and therefore consume bandwidth for reasons the user might not predict. For example, anti-virus packages (such as Norton AntiVirus) periodically update themselves automatically and directly from the Internet. It is better if these updates are distributed from a local server. Other programs, such as the RealNetworks video player, automatically download updates and advertisements, as well as upload usage patterns back to a site on the Internet. Innocuous looking applets (like Konfabulator and Dashboard widgets) continually poll Internet hosts for updated information. These can be low bandwidth requests (like weather or news updates), or very high bandwidth requests (such as webcams). These applications may need to be throttled or blocked altogether. The latest versions of Windows and Mac OS X also have a time synchronization service. This keeps the computer clock accurate by connecting to time servers on the Internet. It is more efficient to install a local time server and distribute accurate time from there, rather than to tie up the Internet link with these requests.

Windows traffic on the Internet link Windows computers communicate with each other via NetBIOS and Server Message Block (SMB). These protocols work on top of TCP/IP or other transport protocols. It is a protocol that works by holding elections to determine which computer will be the master browser. The master browser is a computer that keeps a list of all the computers, shares and printers that you can see in Network Neighborhood or My Network Places. Information about available shares are also broadcast at regular intervals. The SMB protocol is designed for LANs and causes problems when the Windows computer is connected to the Internet. Unless SMB traffic is filtered, it will also tend to spread to the Internet link, wasting the organization's bandwidth. The following steps might be taken to prevent this: Block outgoing SMB/NetBIOS traffic on the perimeter router or firewall. This traffic will eat up Internet bandwidth, and worse, poses a potential security risk. Many Internet worms and penetration tools actively scan for open SMB shares, and will exploit these connections to gain greater access to your network. Install ZoneAlarm on all workstations (not the server). A free version can be found at http://www.zonelabs.com/. This program allows the user to determine which applications can make connections to the Internet and which ones cannot. For example, Internet Explorer needs to

connect to the Internet, but Windows Explorer does not. ZoneAlarm can block Windows Explorer from doing so. Reduce network shares. Ideally, only the file server should have any shares. You can use a tool such as SoftPerfect Network Scanner (from http://www.softperfect.com/) to easily identify all the shares in your network.

Worms and viruses Worms and viruses can generate enormous amounts of traffic. The W32/ Opaserv worm, for example, is still prevalent, even though it is an old one. It spreads through Windows shares and is detected by other people on the Internet because it attempts to spread further. It is therefore essential that anti-virus protection is installed on all PCs. Furthermore, user education about executing attachments and responding to unsolicited email is essential. In fact, it should be a policy that no workstation or server should run unused services. A PC should not have shares unless it is a file server; and a server should not run unnecessary services either. For example, Windows and Unix servers typically run a web server service by default. This should be disabled if that server has a different function; the fewer services a computer runs, the less there is to exploit.

Email forwarding loops Occasionally, a single user making a mistake can cause a problem. For example, a user whose university account is configured to forward all mail to her Yahoo account. The user goes on holiday. All emails sent to her in her absence are still forwarded to her Yahoo account, which can grow to only 2 MB. When the Yahoo account becomes full, it starts bouncing the emails back to the university account, which immediately forwards it back to the Yahoo account. An email loop is formed that might send hundreds of thousands of emails back and forth, generating massive traffic and crashing mail servers. There are features of mail server programs that can recognize loops. These should be turned on by default. Administrators must also take care that they do not turn this feature off by mistake, or install an SMTP forwarder that modifies mail headers in such a way that the mail server does not recognize the mail loop.

Large downloads A user may start several simultaneous downloads, or download large files such as 650MB ISO images. In this way, a single user can use up most of the bandwidth. The solutions to this kind of problem lie in training, offline downloading, and monitoring (including real-time monitoring, as outlined in chapter six). Offline downloading can be implemented in at least two ways: At the University of Moratuwa, a system was implemented using URL redirection. Users accessing ftp:// URLs are served a directory listing in which each file has two links: one for normal downloading, and the other for offline downloading. If the offline link is selected, the specified file is queued for later download and the user notified by email when the downloadis complete. The system keeps a cache of recently downloaded files, and retrieves such files immediately when requested again. The download queue is sorted by file size. Therefore, small files are downloaded first. As some bandwidth is allocated to this system even during peak hours, users requesting small files may receive them within minutes, sometimes even faster than an online download. Another approach would be to create a web interface where users enter the URL of the file they want to download. This is then downloaded overnight using a cron job or scheduled task. This system would only work for users who are not impatient, and are familiar with what file sizes would be problematic for download during the working day.

Sending large files When users need to transfer large files to collaborators elsewhere on the Internet, they should be shown how to schedule the upload. In Windows, an upload to a remote FTP server can be done using an FTP script file, which is a text file containing FTP commands, similar to the following (saved as c:\ftpscript.txt): open ftp.ed.ac.uk gventer mysecretword delete data.zip binary put data.zip quit To execute, type this from the command prompt: ftp -s:c:\ftpscript.txt On Windows NT, 2000 and XP computers, the command can be saved into a file such as transfer.cmd, and scheduled to run at night using the Scheduled Tasks (Start Settings Control Panel Scheduled Tasks). In UNIX, the same can be achieved by using at or cron.

Users sending each other files Users often need to send each other large files. It is a waste of bandwidth to send these via the Internet if the recipient is local. A file share should be created on the local Windows / Samba /web Novell server, where a user can put the large file for others to access. Alternatively, a web front-end can be written for a local web server to accept a large file and place it in a download area. After uploading it to the web server, the user receives a URL for the file. He can then give that URL to his local or international collaborators, and when they access that URL they can download it. This is what the University of Bristol has done with their FLUFF system. The University offers a facility for the upload of large files (FLUFF) available from http://www.bristol.ac.uk/fluff/. These files can then be accessed by anyone who has been given their location. The advantage of this approach is that users can give external users access to their files, whereas the file share method can work only for users within the campus network. A system like this can easily be implemented as a CGI script using Python and Apache.

Economy evaluation of improvised wireless networking


Achieving long-term sustainability is perhaps the most difficult goal when designing and operating wireless networks and telecenters in developing countries. The prohibitive cost of Internet connectivity in many developing countries imposes a substantial operating expense that makes these models sensitive to economic fluctuations and necessitates innovation to attain viability. Substantial progress in the use of wireless networks for rural communications has been accomplished over the past few years, due in large part to technological breakthroughs. Longdistance links have been constructed, high bandwidth designs are possible and secure means to access networks are available. In contrast, there have been fewer successes with the development of sustainable business models for wireless networks and telecenters, particularly for remote areas. In the past decade, there has been tremendous growth in Internet access across the developing world. Most developing world cities now have wireless or ADSL networks and fiber optic connections to the Internet, which is a substantial improvement. Nevertheless, outside urban areas or when the access to the Internet is completely restricted, Internet access is still a formidable challenge. There is little wired infrastructure beyond the principal cities. Therefore, wireless remains one of the few choices for providing affordable Internet access. There are now proven models for rural access using wireless. Two common misconceptions must be dispelled. First, many people assume that there is one preferred business model that will work in every community of the developing world, and the key to success is to find that one eureka solution. In practice, this is not the case. Each community, town or village is different. There is no prescribed model that meets the needs of all areas in the developing world. Despite the fact that some places may be similar in economic terms, the characteristics of a sustainable business model vary from community to community. Although one model may work in one village, another village nearby may not possess the same necessary qualities for this model to be sustainable. Another misconception is that sustainability has the same definition for all people. Although this term generally means that a system is built to persist indefinitely. When determining and implementing the best model for a wireless network or telecenter, several key factors help to ensure its success.

Evaluate the Demand First, identify the individuals, groups and organizations in the community that have a need for information and would benefit from the wireless networks offerings. Potential users could consist of a wide variety of individuals and organizations that include, but are not limited to: Farmers associations and cooperatives Womens groups Schools and universities Businesses and local entrepreneurs Health clinics and hospitals Religious groups International and local non-governmental organizations (NGOs) Local and national government agencies Radio stations Organizations in the tourist industry Then you must determine their needs for access to information and communication.for example a farmaer may need to gather in formation on market prices and climatic conditions to improve his crop yield and sales and can receive this information through SMS over a mobile phone or through Voice over Internet Protocol (VOIP). When assessing the needs of the community, it is important to figure out where the network can bring the most value to its users. You can evaluate the demand in your community by contacting your potential customers and asking questions directly through surveys, focus groups, interviews or town hall meetings.

Establish Appropriate Incentives Establishing appropriate economic incentives is paramount to the success of the network. The network must provide economic value to its users in a way that outweighs its costs, or it must be cheap enough that its costs are marginal and affordable to its users. You should try to answer the following questions: 1. What economic value can this network generate for the local economy and for whom? 2. How much perceivable economic value can be generated? 3. Can present impediments be overcome to allow the achievement of these economic returns? Regulatory Environment for Wireless First, research whether any organization has the right to use 2.4 GHz frequencies without a license. In most situations, 2.4 GHz is free to use worldwide; however, some countries restrict who can operate a network or require expensive licenses to do so You should also check into the legality of Voice over Internet Protocol (VoIP) services. Most countries in the developing world have not yet defined whether VoIP is permitted.

Analyze the Competition Community involves an analysis of the wireless networks competition. Competitors include organizations that provide similar products and services (e.g., another wireless Internet service provider or WISP), organizations viewed as substitutes or alternatives to the products and services your network provides (e.g., a cybercaf), and organizations defined as new entrants to the wireless market. Finally, by analyzing your competitors from the customers point of view and understanding their strengths and weaknesses, you can determine your competitive advantages in the community. Competitive advantages are those which cannot be easily replicated by the competition. For example, a wireless network that can exclusively offer a faster Internet connection than a competitor is a competitive advantage that facilitates client utilization.

Determine Initial and Recurring Costs and Pricing When you are planning to set up and operate your wireless network, you must determine the resources needed to start your project and the recurring operating costs. Start-up costs include everything you must purchase to start your wireless network. These expenses can range from the initial investment you make in hardware, installations, and equipment for access points, hubs, switches, cables, UPS, etc. to the costs to register your organization as a legal entity. Recurring costs are what you must pay to continue to operate your wireless network, including the cost of Internet access, telephone, loans, electricity, salaries, office rental fees, equipment maintenance and repairs, and regular investments to replace malfunctioning or obsolete equipment.

Labor costs

Initial / start-up costs Check ups (analyses) and consultancies Development costs for programming, testing, integration etc. Installation costs Recruiting costs Training costs (introduction) Acquisition and production costs (for hardware like PCs, VSAT, radio link equipment and software) Ancillary equipment (e.g., switches, cables and cabling, generator, UPS, etc.) Data protection and security Start-up inventory (chairs, tables, lighting, curtains, tiles and carpeting) Premises costs (new building, modification, air conditioning, electrical wiring and boxes, security grills) Legal costs, such as business registration Initial license costs (VSAT) Initial marketing costs (flyers, stickers, posters, opening party)

Material (non-labor) costs

Recurring costs Handling costs / salaries for employees or freelancer, including yourself Equipment maintenance and support costs for software, hardware and ancillary equipment Security personnel Training costs (refreshers) Operating costs for hardware and operating systems (Internet access, telephone, etc.) Rent or leasing rates Depreciation of hardware and equipment License fees Consumables and office supplies (e.g., data media, paper, binds, clips) Operational costs to maintain data protection and security Insurance premiums Costs for energy and to ensure power supply Loan payments, capital costs for paying back your setup costs Costs for advertising Local fees Legal and accounting services

To improve your chances of sustainability, it is generally best to maintain the lowest cost structure for your network. In other words, keep your expenses as low as possible. Before installing an expensive VSAT, ensure there is a sufficient number of individuals and organizations in your community willing and able to pay for using it. Depending upon demand for information access and ability to pay, an alternative method of connectivity may be more appropriate. The larger and more complicated your infrastructure becomes the more financial and labor resources you must allocate for its maintenance. A major wireless internet service provider (WISP) who had more than 3,000 access points in operation for a while. However, the WISP never managed to break even because it had to spend

too much money to maintain all the access points. In addition, the company underestimated the short lifecycle of such devices. ICT hardware tends to get cheaper and better as time goes on. As soon as the company had invested time and money to install the version of expensive first generation 802.11b access points, the new g standard was created. New competitors designed better and cheaper access points and offered faster Internet access for less money. Protocol 802.11 802.11b 802.11g 802.11a 802.11y 802.11n Release Date 1997 1999 2003 1999, but rare until 2005 June 2008 (estimated) June 2009 (estimated) Typical Data Rate < 1 Mbps 5 Mbps 20 Mbps 23 Mbps 23 Mbps 75 Mbps

These key tips will assist when making pricing decisions:

Calculate the prices you charge so that you cover all costs to provide the service, including all recurring expenses Examine the prices of your competitors Evaluate what your customers are willing and able to pay for your services, and make sure your prices correspond with these creative models needed to be constructed to reduce the telecenters costs and provide access in a way that was sustainable.

Shared Internet over wireless In above model a traditional VSAT was used for connectivity. However, this model provided a unique way of accommodating local community groups limited ability to pay for Internet services. Various organizations in the com munity share Internet access through a wireless network; they also share the costs associated with that connection. This model functions well due to specific conditions namely an awareness and understanding of the value of the Internet among key community members, the necessary resources to support Internet access, and a regulatory system that permits wireless sharing.

DakNet's roaming access point Another example of a model adapted to fit the local context is that of First Mile Solutions DakNet. This model has been deployed in villages in India, Cambodia, Rwanda, and Paraguay. By taking into account the limited buying power of villagers, this model addresses their communication needs in an innovative way. In the DakNet model, there is a franchise that exists in the country, and local entrepreneurs are recruited and trained to operate kiosks equipped with Wi-Fi antennas. Using pre-paid cards, villagers are able to asynchronously send and receive emails, texts, and voice mails, conduct web searches, and participate in e-commerce. Afterwards, these communications are stored in the local kiosks server. When a bus or motorcycle with a mobile access point drives past a kiosk, the vehicle automatically receives the kiosks stored data and delivers any incoming data. Once the vehicle reaches a hub with Internet connectivity, it processes all requests, relaying emails, messages, and shared files. DakNet integrates both mobile access and franchise models to bring value to people in remote villages. For such a model to be sustainable, several key conditions need to be present. First, a franchise organization must exist to provide financial and institutional support, including an initial investment, working capital for certain recurring costs, advice on start-up practices, management training, standardized processes, reporting mechanisms, and marketing tools. Additionally, this model requires a highly motivated and dynamic individual in the village, with the appropriate skills to manage a business and willingness to accept certain requirements of the franchise organization. Because these entrepreneurs are often asked to commit their own resources to the start-up costs, they need to have sufficient access to financial resources. Finally, to ensure this model will sustain itself, there should be sufficient demand for information and communication and few competitors in the community.

Case study
Timbuktu: client site was only 1 km away directly by line of sight. Two modified Linksys access points, flashed with OpenWRT and set to bridge mode, were installed. One was installed on the wall of the telecentre, and the other was installed 5 meters up the radio station's mast. The only configuration parameters required on both devices were the ssid and the channel. Simple 14 dBi pane antennas (from http://hyperlinktech.com/) were used. At the Internet side, the access point and antenna were fastened using cement plugs and screws onto the side of the building, facing the client site. At the client site, an existing antenna mast was used. The access point and antenna were mounted using pipe rings. To disconnect the client, the telecentre simply unplugs the bridge on their side. An additional site will eventually be installed, and it too will have its own bridge at the telecentre so that staff can physically disconnect the client if they have not paid. Though crude, this solution is effective and reduces risk that the staff would make a mistake while making changes to the configuration of the system. Having a bridge dedicated to one connection also simplified installation at the central site. as the installation team was able to choose the best spot for connecting the client sites. Though it is not optimal to bridge a network (rather than route network traffic), when technology knowledge is low and one wants to install a very simple system this can be a reasonablesolution for small networks. The bridge makes systems installed at the remote site (the radio station) appear as though they are simply connected to the local network.

Cheap Internet in Mali The technical team determined that the access point would be installed at 20 meters up the radio station tower, just below the FM radio dipoles, and not so high as to interfere with coverage to client sites below in the bowl-like depression where most were found. The team then focused on how to connect each client site to this site. An 8 dBi omni (from Hyperlinktech, http://hyperlinktech.com/) would suffice, providing coverage to all client sites. The 8 dBi antenna that was chosen has a 15 degree vertical beamwidth, assuring that the two clients less than a kilometer away could still receive a strong signal. Some antennae have very narrow beam width and thus "overshoot" sites that are close. Panel antennae were considered, though at least two would be required and either a second radio or a channel splitter. It was deemed unnecessary for this installation. The following calculation shows how to calculate the angle between the client site's antenna and the base station's antenna, using standard trigonometry. tan(x) = difference in elevation + height of base station antenna - height of CPE antenna / distance between the sites tan(x) = 5m + 20m - 3m / 400m x = tan-1 (22m / 400m) x =~ 3 degrees

In addition to the equipment in the telecentre (4 computers, a laser printer, 16 port switch), the radio station itself has one Linux workstation installed by the author's project for audio editing. A small switch was installed in the radio station, an Ethernet cable was run through plastic tubing buried at 5 cm across to the telecentre, across the yard. From the main switch, two cables run up to a Mikrotik RB220, access point. The RB220 has two Ethernet ports, one that connects to the VSAT through a cross-over cable, and the second that connects to the radio station's central switch. The RB 220 is housed in a D-I-Y PVC enclosure and an 8 dBi omni (Hyperlink Technologies) is mounted directly to the top of the PVC cap. The RB220 runs a derivative of Linux, Mikrotik version 2.8.27. It controls the network, providing DHCP, firewall, and DNS-caching services, while routing traffic to the VSAT using NAT. The Mikrotik comes with a powerful command line and a relatively friendly and comprehensive graphical interface. It is a small x86 based computer, designed for use as an access point or embedded computer. These access points are POE capable, have two Ethernet ports, a mini-pci port, two PCMCIA slots, a CF reader (which is used for its NVRAM), are temperature tolerant and support a variety of x86 operating systems. Despite that the Mikrotik software requires licensing; there was already a substantial user base in Mali. The system has a powerful and friendly graphical interface that was superior to other products. Due to the above factors the team agreed to use these systems, including the Mikrotik software to control these networks. The total cost of the RB220, with License Level 5, Atheros mini-pci a/b/g and POE was $461. You can find these parts at Mikrotik online at http://www.mikrotik.com/routers.php#linx1part0. The network was designed to accommodate expansion by segregating the various sub-networks of each client; 24 bit private subnets were alloted. The AP has a virtual interface on each subnet and does all routing between, also allowing fire-walling at the IP layer. Note: this does not provide a firewall at the network layer, thus, using a network sniffer like tcpdump one can see all traffic on the wireless link. To limit access to subscribers, the network uses MAC level access control. There was little perceived security risk to the network. For this first phase, a more thorough security system was left to be implemented in the future, when time could be found to find an easier interface for controlling access. Users were encouraged to use secure protocols, such as https, pops, imaps etc. The affiliate project had installed a C-band VSAT (DVB-S) system. These satellite systems are normally very reliable and are often used by ISPs. It is a large unit, in this case the dish was 2.2 meters in diameter and expensive, costing approximately $12,000 including installation. It is also expensive to operate. A 128 kbps down and 64 kbps up Internet connection costs approximately $700 per month. This system has several advantages compared to a Ku system though, including: greater resilience to bad weather, lower contention rates (number of competing users on the same service) and it is more efficient at transferring data. The installation of this VSAT was not ideal. Since the system ran Windows, users were able to quickly change a few settings, including adding a password to the default account. The system had no UPS or battery back up, so once a power outage occurred the system would reboot and sit waiting for a password, which had since been forgotten. To make this situation worse, because the VSAT software was not configured as an automatic background service it did not automatically launch and establish the link. Though the Cband systems are typically reliable, this installation caused needless outages which could have been resolved with the use of a UPS,

proper configuration of the VSAT software as a service, and by limiting physical access to the modem. Like all owners of new equipment, the radio station wanted to display it, hence it was not hidden from view. Preferably a space with glass doors would have kept the unit secure while keeping it visible. The wireless system was fairly simple. All of the client sites selected were within 2 km of the radio station. Each site had a part of the building that could physically see the radio station. At the client site, the team chose to use commercial, client grade CPEs: Based on price, the Powernoc 802.11b CPE bridge, small SuperPass 7 dBi patch antennas and home-made Power Over Ethernet (POE) adaptors. To facilitate installation, the CPE and the patch antenna were mounted on a small piece of wood that could be installed on the outside wall of the building facing the radio station. In some cases the piece of wood was an angled block to optimize the position of the antenna. Inside, a POE made from a repurposed television signal amplifier (12V) was used to power the units. At the client sites there were not local networks, so the team also had to install cable and hubs to provide Internet for each computer. In some cases it was necessary to install Ethernet adapters and their drivers (this was not determined during the assessment). It was decided that because the client's networks were simple, that it would be easiest to bridge their networks. Should it be required, the IP architecture could allow future partitioning and the CPE equipment supported STA mode. We used a PowerNOC CPE bridge that cost $249. Local staff were involved during the installation of the wireless network. They learned everything from wiring to antenna placement. An intensive training program followed the installation. It lasted several weeks, and was meant to teach the staff the day to day tasks, as well as basic network troubleshooting. A young university graduate who had returned to the community was chosen to support the system, except for the cable installation, which the radio station technician quickly learned. Wiring Ethernet networks is very similar to coaxial cable repairs and installations which the radio technician already performed regularly. The young graduate also required little training. The team spent most of its time helping him learn how to support the basics of the system and the telecentre. Soon after the telecentre opened, students were lined up for the computer training, which offered 20 hours of training and Internet use per month for only $40, a bargain compared to the $2 an hour for Internet access. Providing this training was a significant revenue and was a task that the young computer savvy graduate was well suited for. Unfortunately, and somewhat unsurprisingly, the young graduate left for the capital, Bamako, after receiving an offer for a government job. This left the telecentre effectively marooned. Their most technically savvy member, and the only one who was trained in how to support the system, had left. Most of the knowledge needed to operate the telecentre and network left with him. After much deliberation, the team determined that it was best not to train another tech savvy youth, but rather to focus on the permanent local staff, despite their limited technical experience. This took much more time. Our trainers have had to return for a total of 150 hours of training. Several people were taught each function, and the telecentre support tasks were divided among the staff.

Training did not stop there. Once the community services were connected, they too needed access. It seemed that although they were participating, the principals, including the mayor, were not using the systems themselves. The team realized the importance of assuring that the decision makers used the system, and provided training for them and their staff. This did remove some of the mystique of the network and got the city's decision makers involved. Following training, the program monitored the site and began to provide input, evaluating ways that this model could be improved. Lessons learned here were applied to other sites. Wireless Mesh Network in India The Wireless-Mesh Community Network came to life in February 2005, following the deregulation of WiFi for outdoor use in India. By the end of February 2005, the mesh had already connected 8 campuses. Extensive testing during February of 2005 showed that the hard mountainous terrain is most suitable for mesh networking, as conventional point-tomultipoint networks, cannot overcome the line-of-sight limitations presented by the mountains. Mesh topology also offered much larger area coverage, while the self healing nature of mesh routing, proved to be essential in places where electricity supply is very erratic at best. The mesh backbone includes over 30 nodes, all sharing a single radio channel. Broadband Internet services are provided to all mesh members. The total upstream Internet bandwidth available is 6 Mbps. There are over 2,000 computers connected to the mesh, the broadband internet connection is putting the mesh under great load. At present, the system seems to handle the load without any increase in latency or packet-loss. It is clear that scalability will become an issue if we continue to use a single radio channel. To solve this problem, new mesh routers with multiple radio channel support are being developed and tested , with an emphasis on products that meet the technical requirements The mesh network is based on recurring deployments of a hardware device, which is designed and built locally known as the Himalayan-Mesh-Router (http://drupal.airjaldi.com/node/9). The same mesh-routers are installed at every location, with only different antennas, depending on the geographical locations and needs. We use a wide range of antennas, from 8 - 11 dBi omnidirectional, to 12 - 24 dBi directional antennas and occasionally some highgain (and cost) sector antennas. The mesh is primarily used for: Internet access File-sharing applications Off-site backups Playback of high quality video from remote archives. A central VoIP, software-based PBX is installed (Asterisk) and it provides advanced telephony services to members. The Asterisk PBX is also interfacing the PSTN telephone network. However, due to legal issues it is presently used only for incoming calls into the mesh. Subscribers use a large variety of software-phones, as well as numerous ATAs (Analog Telephone Adaptors) and full-featured IP phones.

The encrypted mesh back-bone does not allow access to roaming mobile devices (notebooks and PDAs), so we have placed multiple 802.11b accesspoints at many of the same locations where mesh-routers are installed. The mesh provides the backbone infrastructure while these APs provide access to mobile roaming devices, where needed. Access to the mesh back-bone is only possible by mesh-routers. Simple wireless clients lack the intelligence needed to speak the mesh routing protocols and strict access policies. The mesh channel is therefore encrypted (WPA), and also hidden to prevent mobile devices from finding it or attempting to access it. Allowing access to the mesh only by mesh-routers allows for strict access control policies and limitations to be enforced at the CPE (Client Premises Equipment) which is a crucial element needed to achieve end-toend security, traffic-shaping, and quality-ofservice. Power consumption of the mesh-Router is less than 4 Watts. This makes them ideal for using with solar panels. Many of the Dharamsala Mesh routers are powered solely by small solar panels. The use of solar power in combination with small antennas and low power routers is ideally suitable for disaster areas, as it very likely to survive when all other communication infrastructure is damaged.

Venezuela: Packet radio Local amateurs operate a packet radio network. Initially it worked at 1200 bps, using VHF amateur FM voice radios connected to a personal computer by means of a terminal node controller (TNC). The TNC is the interface between the analog radio and the digital signals handled by the PC. The TNC keys the Push To Talk circuits in the radio to change from transmit to receive, performs modulation/demodulation and the assembly/disassembly of packets using a variation of the X.25 protocol known as AX.25. Gateways between VHF and HF radios were built by attaching two modems to the same TNC and computer. Typically, a gateway would connect the local VHF packet network to stations overseas by means of HF stations that could span thousands of kilometers, albeit at a speed of only 300 bps. A national packet radio network was also built, which relayed on digipeaters (digital repeaters, essentially a TNC connected to two radios with antennas pointing in different directions), to extend the network from Mrida to Caracas by means of just two such repeater stations. The digipeaters operated at 1200 bps and allowed for the sharing of programs and some text files among amateurs. Phil Karn, a radio amateur with a strong background in computer networks, wrote the KA9Q program that implements TCP/IP over AX.25. Using this program, named after the call sign of its developer, amateurs all over the world were soon able to connect to the Internet using different kinds of radios. KA9Q keeps the functions of the TNC to a bare minimum, harnessing the power of the attached PC for most processing functions. This approach allows for much greater flexibility and easy upgrades. In Mrida, we were soon able to upgrade our network to 9600 bps by use of more

advanced modems, and several radio amateurs were now able to access the Internet through the RedULA wired network. The limit on the radio bandwidth available on the VHF band puts a cap on the highest attainable speed. To increase that speed, one must move to higher frequency carriers. Amateurs are allowed to use 100 kHz wide channels using UHF (Ultra-High Frequency) signals. Digital radios coupled with 19.2 kbps modems doubled the transmission bandwidth. A project was developed using this technology to link the House of Science in the city of El Vigia, to Mrida and the Internet. UHF antennas were built at LabCom, the communications laboratory of ULA.

A UHF antenna for packet radio developed at ULA, LabCom. Although El Vigia is only 100 km from Mrida by road, the mountainous terrain called for the use of two repeaters. One is located at La Aguada, at 3600 m altitude, and the other at Tusta, at 2000 m. The project was financed by FUNDACITE MERIDA, a government institution that promotes science and technology in the state. FUNDACITE also operates a pool of 56 kbps telephone modems to provide Internet access for institutions and individuals. The need for two repeater stations underscores the limitations imposed by using higher frequency carriers, which require line of sight to establish a reli able transmission. In the much lower VHF band, signals are easily reflected and can reach beyond hills. Sometimes it is possible to reflect signals using a passive repeater, which is made by connecting two directional antennas back to back with a coaxial cable, without any radio. This scheme was tested to connect my residence to LabCom. The distance is only 11 km, but there is a hill in between that blocks radio signals. A connection was made by using a passive repeater to reflect off La Aguada, with the two antennas of the repeater pointing 40 degrees apart. While this was very exciting and certainly much cheaper than access through the telephone modems, a faster medium would obviously be needed for a wireless backbone to connect remote villages. We therefore explored the use of 56 kbps modems developed by Dale Heatherington. These modems are housed in a PI2 card built by Ottawa amateurs, and connected directly to a PC using Linux as the network operating system. While this system functions very well, the emergence of

the World Wide Web with its plethora of images and other bandwidth-hogging files made it clear that if we were to satisfy the needs of schools and hospitals we had to deploy a higher bandwidth solution, at least on the backbone. This meant the use of even higher carrier frequencies in the microwave range, which entailed high costs. Fortunately, an alternative technology widely used in military applications was becoming available for civilian uses at affordable prices. Called spread spectrum, it first found a use in civilian applications as a short-reach wireless local area network, but soon proved to be very useful in places where the electromagnetic spectrum is not overcrowded, allowing the bridging of distances of several kilometers.

Spread spectrum Spread spectrum uses low power signals with its spectrum expanded on purpose to span all the allocated bandwidth, while at the same time allowing a number of users to share the medium by using different codes for each subscriber. There are two ways to accomplish this: Direct Sequence Spread Spectrum (DSSS) and Frequency Hopping Spread Spectrum (FHSS). In DSSS the information to be transmitted is digitally multiplied by a higher frequency sequence, thereby augmenting the transmission bandwidth. Although this might seem to be a waste of bandwidth, the recovery system is so efficient that it can decode very weak signals, allowing for the simultaneous use of the same spectrum by several stations. In FHSS, the transmitter is constantly changing its carrier frequency inside the allotted bandwidth according to a specified code. The receiver must know this code in order to track the carrier frequency. Both techniques exchange transmission power for bandwidth, allowing many stations to share a certain portion of the spectrum. During the First Latin American Networking School (EsLaRed '92), held in Mrida in 1992, we were able to demonstrate this technique. We established some trial networks making use of external antennas built at the LabCom, allowing transmission at several kilometers. In 1993, the Venezuelan Ministry of Telecommunications opened up four bands for use with DSSS: 400 - 512 MHz 806 - 960 MHz 2.4 - 2.4835 GHz 5.725 - 5.850 GHz In any of the above bands, maximum transmitter power was restricted to 1 Watt and the maximum antenna gain to 6 dBi, for a total EIRP (effective isotropic radiated power) of 36 dBm. This ruling paved the way for the deployment of a DSSS network with a nominal bandwidth of 2 Mbps in the 900 MHz band. This technology satisfied the needs caused by the surge in World Wide Web activity.

The network started at LabCom, where the connection to RedULA was available. LabCom housed an inhouse-built Yagi antenna pointed towards a corner reflector at Aguada. This provided a 90 degree beamwidth, illuminating most of the city of Mrida. Several subscriber sites, all sharing the nominal 2 Mbps bandwidth, were soon exchanging files, including images and video clips. Some subscriber sites that required longer cables between the antenna and the spread spectrum radio were accommodated by the use of bidirectional amplifiers. These encouraging results were reported to a group set up at the International Centre for Theoretical Physics (ICTP) in Trieste, Italy, in 1995. This group was aimed at providing connectivity between the Computer Center, Physical Sciences Building, and the Technology Building at the University of Ile-Ife in Nigeria. Later that year, the network was set up by ICTP staff with funding from the United Nations University and has been running satisfactorily ever since, proving to be a much more cost-effective solution than the fiber optic network originally planned would have been. Back in Mrida, as the number of sites increased, the observed throughput per user declined. We started looking at the 2.4 GHz band to provide additional capacity. This band can carry three simultaneously independent 2 Mbps streams, but the effective range is lower than what can be achieved in the 900 MHz band. We were very busy planning the extension of the backbone using 2.4 GHz when we found out about a start-up company that was offering a new solution that promised longer distances, dramatically higher throughput, and the possibility of frequency reuse with narrowband microwaves. Broadband delivery system After visiting the Nashua, New Hampshire, facilities of Spike Technologies, we were convinced that their proprietary antenna and radio system was the best solution for the requirements of our state network, for the following reasons: Their broadband delivery system employs a special sectored antenna (Figure below), with 20 dBi gain on each of up to 22 independent sectors. Each sector transmits and receives on independent channels at 10 Mbps full duplex, for an aggregate throughput of 440 Mbps. Frequency reuse on interleaved sectors makes for a spectrally efficient system.

Spike Technologies' full duplex, high density sectoral system The narrowband digital radios can operate anywhere from 1 to 10 GHz, with a coverage of up to 50 km. The radios work with a variety of cable TV modems, delivering a standard 10Base-T LAN connection to the subscriber. At the base station, the sectors are interconnected with a highspeed switch that has a very small latency (see Figure below), allowing applications such as streaming video at up to 30 frames per second. Each sector acts as an independent Ethernet LAN.

Spike Technologies' system interconnections

At the subscriber site, a similar radio and modem provide a 10BaseT connection to the local Ethernet.

The subscriber end of the link. With funding from Fundacite, a trial system was soon installed in Mrida, with the base station located just above the cable car station of La Aguada at an altitude of 3600 m.

Installation above Mrida at La Aguada, at 3600 meters.

Chilesincables.org and wirless networking Chilesincables.org endeavors to promote and organize wireless free networks in Chile in a professional way. Description of technology We employ a variety of wireless technologies, including IEEE 802.11a/b/g. We are also investigating recent innovations in the field, such as WiMAX. In most cases, the equipment has been modified in order to be accept external locally built antennas which meet local telecommunications regulations. Even though a majority of wireless hardware available on the market will suit our goals, we encourage utilization and exploration of a few vendors that allow for better control and adaptation to our needs (without necessarily increasing the prices). These include Wi-Fi cards with chipsets offered by Atheros, Prism, Orinoco, and Ralink, as well as some models of access points manufactured by Linksys, Netgear, and Motorola. The hacker community has developed firmware that provides new functionality on this equipment. For the network backbone itself, we employ Open Source operating systems, including GNU/Linux, FreeBSD, OpenBSD, and Minix. This fits our needs in the areas of routing as well as implementation of services such as proxies, web and FTP servers, etc. In addition, they share our projects philosophy of being free technology with open source code.

Uses and applications The networks implemented so far allow the following tasks: Transfer of data via FTP or web servers VoIP services Audio and video streaming Instant messaging Exploration and implementation of new services such as LDAP, name resolution, new security methods, etc. Services provided by the clients. The users are free to use the nets infrastructure in order to create their own services.

Administration and maintenance The operational unit of the network is the node. Each node allows clients to associate to the network and obtain basic network services. In addition, each node must be associated to at least another node, by convention. This allows the network to grow and to make more services available to every client. A node is maintained by an administrator who is a member of the community committed to the following tasks:

Maintenance of an adequate uptime (over 90%). Providing basic services (typically web access). Keeping the clients updated about the nodes services (for example, how to get access to the network). This is generally provided by a captive portal. The general administration of the network (specifically, tasks related to deployment of new nodes, selection of sites, networks topology, etc.) is carried out by the board of the community, or by technicians trained for this purpose. Chilesincables.org is currently in the process of acquiring legal organization status, a step that will allow the regulation of its internal administrative procedures and the formalization of the community in our society. Chilesincables.org undertakes the following activities: Antenna Workshop. Attendees are trained in the construction of antennas, and introduced to basic concepts of radio communication. Operating Systems Workshop. Training on the implementation of routers and other devices based on GNU/Linux or other software such as m0n0wall or pfsense. Basic networking concepts are also taught. Promotion and Advertising. Events for different communities that pursue our same goals are promoted. These include college workshops, lectures, free software gatherings, etc. Updating of Materials. Chilesincables.org maintains a number of freeaccess documents and materials made available to people interested in a specific activity.

Action Plan for long range wifi 802.11 Once satisfied with the existence of a suitable trajectory, we looked at the equipment needed to achieve the goal. We have been using Orinoco cards for a number of years. Sporting an output power of 15 dBm and receive threshold of -84 dBm, they are robust and trustworthy. The free space loss at 282 km is 149 dB. So, we would need 30 dBi antennas at both ends and even that would leave very little margin for other losses. On the other hand, the popular Linksys WRT54G wireless router runs Linux. The Open Source community has written several firmware versions for it that allow for a complete customization of every transmission parameter. In particular, OpenWRT firmware allows for the adjustment of the acknowledgment time of the MAC layer, as well as the output power. Another firmware, DD-WRT, has a GUI interface and a very convenient site survey utility. Furthermore, the Linksys can be located closer to the antenna than a laptop. So, we decided to go with a pair of these boxes. One was configured as an AP (access point) and the other as a client. The WRT54G can operate at 100 mW output power with good linearity, and can even be pushed up to 200 mW. But at this value, non linearity is very severe and spurious signals are generated, which should be avoided. Although this is consumer grade equipment and quite inexpensive, after years of using it, we felt confident that it could serve our purpose. Of course, we kept a spare set handy just in case. By setting the output power to 100 mW (20 dBm), we could obtain a 5dB advantage compared with the Orinoco card. Therefore, we settled for a pair of WRT54Gs.

Appendix A: Channel Allocations


The following tables list the channel numbers and center frequencies used for 802.11a and 802.11b/g. Note that while all of these frequencies are in the unlicensed ISM and U-NII bands, not all channels are available in all countries. Many regions impose restrictions on output power and indoor / outdoor use on some channels. These regulations are rapidly changing, so always check your local regulations before transmitting. Note that these tables show the center frequency for each channel. Channels are 22MHz wide in 802.11b/g, and 20MHz wide in 802.11a. 802.11b / g Center Frequency Channel (GHz) # 2.412 8 2.417 9 2.422 10 2.427 11 2.432 12 2.437 13 2.442 14 802.11a Channel # 34 36 38 40 42 44 46 48 52 56 60 64 149 153 157 161 Center Frequency (GHz) 5.170 5.180 5.190 5.200 5.210 5.220 5.230 5.240 5.260 5.280 5.300 5.320 5.745 5.765 5.785 5.805

Channel # 1 2 3 4 5 6 7

Center Frequency (GHz) 2.447 2.452 2.457 2.462 2.467 2.472 2.484

Appendix B: Path Loss


Free-space path loss in decibels: For typical radio applications, it is common to find measured in units of GHz and in km, in which case the FSPL equation becomes:

For

in meters and megahertz, respectively, the constant becomes

The expression for FSPL actually encapsulates two effects. Firstly, the spreading out of electromagnetic energy in free space is determined by the inverse square law, i.e.

Where:

is the power per unit area or power spatial density (in watts per metre-squared) at distance , is the total power transmitted (in watts).

Note that this is not a frequency-dependent effect. The second effect is that of the receiving antenna's aperture, which describes how well an antenna can pick up power from an incoming electromagnetic wave. For an isotropic antenna, this is given by

Where is the received power. Note that this is entirely dependent on wavelength, which is how the frequency-dependent behaviour arises. The total loss is given by the ratio

Which can be found by combining the previous two expressions.

Affect of antenna gain on path loss equation The equation above does not include any component for antenna gains. It is assumed that the antenna gain is unity for both the transmitter. In reality, though, all antennas will have a certain amount of gain and this will affect the overall affect. Any antenna gain will reduce the "loss" when compared to a unity gain system. The figures for antenna gain are relative to an isotropic source, i.e. an antenna that radiates equally in all directions.

FSPL (dB) = 20 log 10 (d) + 20 log 10 (f) + 32.44 -Gtx - Grx Where: Gtx is the gain of the transmitter antenna relative to an isotropic source (dBi) Grx is the gain of the receiver antenna relative to an isotropic source (dBi) The free space path loss equation or formula given above, is an essential tool that is required when making calculations for radio and wireless systems either manually or within applications such as wireless survey tools, etc. By using the free space path loss equation, it is possible to determine the signal strengths that may be expected in many scenarios. While the free space path loss formula is not fully applicable where there are other interactions, e.g. reflection, refraction, etc as are present in most real life applications, the equation can nevertheless be used to give an indication of what may be expected. It is obviously fully applicable to satellite systems where the paths conform closely to the totally free space scenarios. .......

For 5.3 GHz , the curve shifts about to 5dB higher

What is link budget? As the name implies, a link budget is an accounting of all the gains and losses in a transmission system. The link budget looks at the elements that will determine the signal strength arriving at the receiver. The link budget may include the following items:

Transmitter power. Antenna gains (receiver and transmitter). Antenna feeder losses (receiver and transmitter). Path losses. Receiver sensitivity (although this is not part of the actual link budget, it is necessary to know this to enable any pass fail criteria to be applied.

Where the losses may vary with time, e.g. fading, and allowance must be made within the link budget for this - often the worst case may be taken, or alternatively an acceptance of periods of increased bit error rate (for digital signals) or degraded signal to noise ratio for analogue systems. In essence the link budget will take the form of the equation below:

Received power (dBm) = Transmitted power (dBm) + gains (db) - losses (dB)

The basic calculation to determine the link budget is quite straightforward. It is mainly a matter of accounting for all the different losses and gains between the transmitter and the receiver.

Link budget equation In order to devise a link budget equation, it is necessary to investigate all the areas where gains and losses may occur between the transmitter and the receiver. Although guidelines and suggestions can be made regarding the possible areas for losses and gains, each link has to be analysed on its own merits.. A typical link budget equation for a radio communications system may look like the following: PRX = PTX + PTX + GTX + GRX - L TX - LFS - L P - LRX Where: PRX = received power (dBm) PTX = transmitter output power (dBm)

GTX = transmitter antenna gain (dBi) GRX = receiver antenna gain (dBi) LTX = transmit feeder and associated losses (feeder, connectors, etc.) (dB) LFS = free space loss or path loss (dB) LP = miscellaneous signal propagation losses (these include fading margin, polarization mismatch, losses associated with medium through which signal is travelling, other losses...) (dB) LRX = receiver feeder and associated losses (feeder, connectors, etc.) (d)B NB for the sake of showing losses in the link budget equation is "minus" actual loss figures, e.g. LTX or LFS, etc should be taken as the modulus of the loss.

Appendix C: Cable Sizes


Wire gauge, diameter, current capacity, and resistance at 20C. These values can vary from cable to cable. When in doubt, consult the manufacturer's specifications. AWG Gauge 0000 000 00 0 1 2 3 4 5 6 7 8 9 10 Diameter (mm) 11.68 10.40 9.27 8.25 7.35 6.54 5.83 5.19 4.62 4.11 3.67 3.26 2.91 2.59 Ohms / Meter 0.000161 0.000203 0.000256 0.000322 0.000406 0.000513 0.000646 0.000815 0.001028 0.001296 0.001634 0.002060 0.002598 0.003276 Max Amperes 302 239 190 150 119 94 75 60 47 37 30 24 19 15

OpenWrt
OpenWrt is a Linux distribution primarily targeted at routing on embedded devices. It comprises a set of about 2000 software packages, installed and uninstalled via the opkg package management system. OpenWrt can be configured using the command-line interface of BusyBox ash, or the web interface LuCI. OpenWrt can be run on CPE routers, residential gateways, smartphones (e.g. Neo FreeRunner), pocket computers (e.g. Ben NanoNote), and small laptops (e.g. One Laptop per Child (OLPC)). But it is also possible to run on ordinary computers (e.g. x86). The project incorporates a wiki, a forum, SVN source version control and Trac for project management, bug-tracking, and code development. Additional technical support is also provided via Internet Relay Chat (IRC).

Features
The features include:

A writable root file system, enabling users to add, remove or modify any file. This is accomplished by using mini_fo to overlay a read-only compressed SquashFS file system with a writable JFFS2 file system in a copy-on-write fashion. Flash wear leveling using JFFS2. The package manager opkg, similar to dpkg or pacman, which enables users to install and remove software. This contrasts with Linux-based firmware based on read-only file systems that offer efficient compression but no way to modify the installed software without rebuilding and flashing a complete firmware image. A package repository containing about 2,000 packages, chiefly ones suited for an environment with limited resources. Sysupgrade, preserving selected configuration files on firmware upgrade. a set of scripts called UCI (unified configuration interface) intended to unify and simplify the configuration of the entire system extensible configuration of your network involving VLAN with exhaustive possibilities to configure the routing itself customizable methods to filter, manipulate, delay and rearrange network packets: o Firewall o Port Forwarding of external traffic to computers behind NAT inside the LAN o Quality of Service for simultaneous use of applications such as VoIP, online gaming, and streaming media o Traffic shaping to ensure fair distribution of bandwidth among users o Load balancing for use with multiple ISPs o IP tunneling o Realtime network monitoring and statistics Static DHCP leases UPnP and NAT-PMP for dynamically configured port forwarding Use of Dynamic DNS services to maintain a fixed domain name with an ISP that does not provide a static IP address On devices with USB ports only: o 3G modem support o Printer sharing o Windows-compatible file sharing (via SAMBA) o File sharing via NFS and FTP o Audio/Video streaming via DLNA/UPnP AV o iTunes (DAAP) server o Webcam streaming o USB audio An extensive Ajax-enabled web interface, thanks to the LuCI project Configuration of the device as a wireless repeater, wireless access point, wireless bridge, or a combination of these Mesh networking User-configurable hardware buttons

Regular bug fixes and updates, even for devices no longer supported by their manufacturers
Web interface

A screenshot of the LuCI web interface used by version 10.03.1-RC5 of OpenWrt. Here it is being used to configure the firewall. Before release 8.09, OpenWrt had a minimal web interface. In release 8.09 a new, more capable web interface is included. This interface is based on LuCI, an MVC framework written in Lua. The X-Wrt project provides an alternate web interface, webif, for current and previous version of OpenWrt. It has more than 40 control and status pages.

1. Introduction 1.1. What is OpenWrt 2. Wireless networking. 2.1. What about Wireless 2.2. What's the max distance between radio cards? 2.3. What's the difference between wired and wireless networks? 2.4. Wireless network access modes. 2.5. Security in wireless networks. 3. Installing OpenWrt 3.1. Hardware 3.1.1. How can I identify which hardware I have? 3.1.2. Units that considered supported in the stable version (eg. known to work "out-ofthe-box"). 3.1.3. Additional units supported in the experimental version. 3.1.4. Units that should work. (untested) 3.1.5. Units known to not work yet. 3.2. Getting the firmware. 3.3. Installing the firmware. 3.3.1. Enabling boot_wait 3.3.2. Using boot_wait to upload the firmware 4. Using OpenWrt 4.1. Using OpenWrt for the first time 4.2. Firstboot / jffs2. 4.3. Editing Files. 4.4. ipkg

5. OpenWrt configuration. 5.1. NVRAM 5.2. Network configuration. 5.3. Wireless Configuration 5.4. Static Routes 5.5. Sample network configurations. 5.5.1. AP mode. 5.5.2. Client mode. 5.6. Finding and joining networks 6. Troubleshooting 6.1. Failsafe mode 6.2. Resetting to defaults 6.3. Recovering from bad firmware

1. Introduction
Wireless networking technology is growing nowadays; there is all kind of devices available. Bridging, routing Ad-Hoc and whatever is out there you can buy it today but we always searching for a cheap way of getting professional equipment. There were people who packed 486 boxes with pcmcia2isa cardbus converters and pcmcia wireless cards in waterproof boxes and would stick them up there roof, hoping that the harddisk isn't freezing in the winter, or that the cpu run's to hot in summer. Back than outdoor router where real expensive and so wireless community networks where growing slow. We were always hoping that one day someone find a real smart solution for that. The OpenAP project seems to be a solution, but it is not to easy to install OpenAP on wireless access point and the hardeware wasn't manufactured for long. So OpenAp is useless and we were still searching for the ultimate solution, till we found OpenWrt. Anyway OpenWrt is not just usefull if you build outdoor community networks; it's so scalable that you can do almost all with it.

1.1. What is OpenWrt OpenWrt is a Linux distribution for the Linksys WRT54G. Instead of trying to cram every possible feature into one firmware, OpenWrt provides only a minimal firmware with support for add-on packages. For users this means the ability to custom tune features, removing unwanted packages to make room for other packages and for developers this means being able to focus on packages without having to test and release an entire firmware.

2. Wireless networking.
2.1. What about Wireless Wireless is a new technology that can help you to connect computers at distance. It works with Wireless cards with a TX/RX inside at 2.4 GHz/5 GHz while the software interface is Ethernetlike, with a hardware address different for each card in the world. Typical transmit power is 1020 mW till 100mW (see standard IEEE 802.11 and FCC/CEPT licenses).

2.2. What's the max distance between radio cards? The most important thing in Wireless communications is the line of sight clear: you MUST SEE (with eyes or with a binocular) the antenna from the other end or you can have (at most) a little tree between them. The distance depends on the antenna and (eventually amplifier) used: 2-300 meters with an omnidirectional antenna; 1 km with a directive one; 2-3 km with an omnidirectional amplified (200mW); some km with parabolic antenna. 50-60 km with parabolic or directive antenna amplified (some Watts). Be aware that it is not always legal to amplifier Wireless cards, cause you could violate FCC/CEPT (and also your country relative) specifics.

2.3. What's the difference between wired and wireless networks? I assume that you are already familiar with the basics of wired networks, at least you should know what is an IP used for and what routing does in a network. When I speak about networks I mean a group of computers which share the same Ip address space. This could be a LAN, WAN or even a MANET (Mobile ad-hoc network). Wired networks are very simple to setup (at least at low level). Wireless networks are very difficult to setup, to manage, to debug... Typical problem with wired networks like hardware install, software install, debug , become very critical with Wireless: In wired networks we got IP addresses which help us to distinguish between different computers or networks. Thats not so different from wireless networks, here are also IP addresses used, but there is a tiny difference. While in wired networks we got wires to separate our networks physically we are not physically separated in wireless networks. This means more networks share one physical area. To be able to

separate between different networks in a wireless network we got some parameters to help us knowing which computers or nodes are in our network group.

ESSID : The ESSID is basically a name used to define a wireless network group, if you have ever used Windows Filesharing or Samba you are familiar with Workgroups, an ESSID is very similar to that, it helps us to know which nodes are in our network. CHANNEL: The bandwidth used by a wireless devices is divided into channels, this basically reduce radio noise produced from other wireless network groups in our area. Think on a walkie talkie, you got different channels, and when one channel is in use by someone you have to use another one, in a wireless network different network groups can share one channel, but when they get more it will get noise.

Note: In the US are 11 channels. In Europe are 13 channels. There is one more parameter which is not so important but we will mention it here. Since there are wireless devices which can handle different data transmission rates, they need a way to deal a data transmission rate of which both devices are capably, when they negotiate. Therefore is the RATE parameter. The default setting of this parameter is "auto" and should not be changed until you really know what you are doing.

2.4. Wireless network access modes. There are two types of wireless networks; the difference is in how the nodes access each other.

AdHoc mode (also called Independent mode), where you have independent networks with a BSS (Basic Service Set) each one. Each station has the same BSS. In this mode all nodes are independent from each other, every node can talk to all nodes close enough to send and receive radio signals. It's a decentralize network structure Infrastructure mode, where a number of networks (with a BSS each one) can communicate with each other by using an Access Point, it's a more centralized network, easier to manage. But if the Access Point fail's for some reason and there is no other to take over the whole network managed by this Access Point is down. Also there is a roaming function letting a station "attach" to the nearer Access Point.

Adhoc is the simpler method (and the also the less scalable) and let many hosts communicate each other directly. The restrictive requirement is that all one are to be visible directly to reach a complete coverage of the network. (At least ideally, because this problem could be solved at IP level).

Adhoc mode A - - - - \ / | \ / /\ | / \ / \ B - - - - C | | D

In an Infrastructure environment you use the Access Point to which ALL other hosts must connect to share the network.

Infrastructure mode ESS A - - - | - Access Point - - Access Point - | - - - D B - - - | BSS1 C---| BSS2 |---E |---F

B and C could not see D, E and F, but they can communicate as well because all one are using the same ESS. Important: A, B and C could also not see each other.

2.5. Security in wireless networks. There has been different security methods developed, since wireless networks are very open to attacks. But while this guide is written for open community networks, I will not go to discuss this here.

3. Installing OpenWrt
3.1. Hardware 3.1.1. How can I identify which hardware I have? 3.1.1.1. Linksys models On the bottom of the device is a silver sticker with a Linksys logo on it, under this logo are the words "Model No." followed by the model number of the device (WRT54G, WRT54GS, WAP54G). If there isn't a version number (v1.1, v2.0, v2.2) after the model then it's a v1.0 device. Note: If you have a WRT54G v2.2 or a WRT54GS v1.1 then OpenWrt will not yet run on these models. Read on the OpenWrt forum: http://openwrt.org/forum for more information on the experimental releases for these models

3.1.2. Units that considered supported in the stable version (e.g. known to work "out-ofthe-box").

Asus WL-500B (version 1.0) Asus WL-500G Buffalo WBR-G54 Buffalo WLA-G54 Linksys WAP54G (version 1.0) Linksys WRT54G (version 1.0, 1.1, and 2.0) Linksys WRT54GS (version 1.0) Siemens SE505 U.S ROBOTICS USR5430 (similar to WAP54g, ...TFTP is factory enabled)

3.1.3. Additional units supported in the experimental version.


Asus WL-500G Deluxe (aka WL-500GD) Buffalo WBR2-G54 Buffalo WLA2-G54L Linksys WRT54G (version 2.2 and 3.0) Linksys WRT54GS (version 1.1 and 2.0) Motorola WR850G Microsoft MN-700

3.1.4. Units that should work. (Untested)


Asus WL-300G Asus WL-500B (version 2) Asus WL-HDD Belkin F5D7130 Belkin F5D7231-4 Belkin F5D7231-4P Belkin F5D8230-4 Buffalo WBR-B11 Buffalo WBR2-B11 Buffalo WBR2-G54S Buffalo WHR-G54 Buffalo WHR2-G54 Buffalo WHR3-G54 Buffalo WLA-G54C Buffalo WLA2-G54 Buffalo WLA2-G54C Buffalo WLI2-TX1-G54 Buffalo WZR-RS-G54 Dell TrueMobile 2300 Linksys WAP54G (version 2) Linksys WAP55AG (version 1) Linksys WRT54GX Linksys WRT55AG (version 1) Motorola WA840G Motorola WA840GP Motorola WR850GP Netgear FWAG114NA Ravotek W54-AP Ravotek W54-RT Siemens SX550 SimpleTech SimpleShare Office Storage Server 250G Sitecom WL-111 Svec FD2164 Toshiba WRC-1000 Trendnet TEW-410APB Trendnet TEW-410APBplus Trendnet TEW-411BRP Trendnet TEW-411BRPplus

3.1.5. Units known to not work yet.


Belkin F5D7230-4 -- only 2M of flash Netgear WGT634U Netgear WG602 (version 3) -- only 2M of flash

3.2. Getting the irmware. It is recommended to download the daily snapshots from the OpenWrt website: http://downloads.openwrt.org . http://cyberforat.squat.net/openwrt/binary_images/linksys_official Last but not least, there is the OpenWrt CVS. If it is the first time that you compile binaries from source, I would recommend to the two first possibilities. Otherwise go ahead and get the latest CVS. $ cvs -d:pserver:anonymous@openwrt.org:/openwrt co buildroot

3.3. Installing the firmware. Note: LOADING AN UNOFFICIAL FIRMWARE WILL VOID YOUR WARRANTY OpenWrt is an unofficial firmware which is neither endorsed nor supported by Linksys or any other vendor. OpenWrt is provided "AS IS" and without any warranty under the terms of the GPL. To avoid potentially serious damage to your router caused by an unbootable firmware we strongly suggest enabling a setting known as boot_wait.

3.3.1. Enabling boot_wait

The router does not boot directly into the firmware, instead it boots into a program known as a bootloader which is responsible for initializing the hardware and loading the firmware. If the boot_wait variable is set, the bootup process is delayed by few seconds allowing a new firmware to be installed through the bootloader using TFTP. Setting of the boot_wait variable is done through a bug in the Ping.asp administration page by pinging the certain "addresses" listed below First, for this to work the "internet port must have a valid ip address", either from DHCP or manually configured from the main page - the port itself doesn't need to be connected unless using DHCP. Next, navigate to the Ping.asp page and enter exactly each line listed below, one line at a time into the "IP Address" field, pressing the Ping button after each entry. ;cp${IFS}*/*/NVRAM${IFS}/tmp/n ;*/n${IFS}set${IFS}boot_wait=on ;*/n${IFS}commit ;*/n${IFS}show>tmp/ping.log

When you get to the last command the ping window should be filled with a long list of variables including "boot_wait=on" somewhere in that list. This ping exploit definitely works with WRT54G v2.0/GS v1.0 and there are documented cases of it working for the latest hardware release WRT54G v2.2/GS v1.1. You must have an address on the WAN port. In the Setup/Basic Setup/Internet Setup section you may wish to select Static IP and set IP=10.0.0.1, Mask=255.0.0.0, Gateway=10.0.0.2. Those values are meaningless; you'll be overwriting them soon with new firmware. Note: flashing a Linksys WRT54GS v1.1 via TFTP using is only possible using the Port 1 of the switch!

3.3.2. Using boot_wait to upload the firmware Although the firmware can be installed through more traditional means, we recommend that you use boot_wait for your first install. This will confirm boot_wait is correctly enabled and provide a firmware recovery experience without the stress of a broken router. While in the bootloader the Linksys wrt54g(s) will be forced to a lan ip of 192.168.1.1. To use the bootloader's TFTP server you need to use a standard TFTP client -- the TFTP clients provided by linksys will not work for this. The file to be uploaded depends on the model; non linksys models take a TRX file while linksys models take a BIN file. Table 1. Firmwares Model Firmeware

WRT54G openwrt-g-code.bin WRT54GS openwrt-gs-code.bin (other) openwrt-linux.trx

The BIN file is simply a TRX with some extra information at the start to indicate the model. The only difference between openwrt-g-code.bin and openwrt-gs-code.bin is the first 4 bytes which determine the model. The basic procedure of using boot_wait is:

unplug the power to your router start your TFTP client o give it the router's address (always 192.168.1.1)

set mode to octet Tell the client to resend the file, until it succeeds. put the file plug your router, while having the TFTP client running and constantly probing for a connection the TFTP client will receive an ack from the bootloader and starts sending the firmware
o o o

Please be patient, the reflashing occurs AFTER the firmware has been transferred. DO NOT unplug the router, it will automatically reboot into the new firmware. OpenWrt will light the DMZ led while booting, after bootup it will turn the DMZ led off

Table 2. LED LED pattern Solid power & DMZ flashing power, slow flashing dmz reason OpenWrt is booting or (if prolonged) has failed to boot, try failsafe mode. (Usually caused by old/corrupt jffs2 data from a previous OpenWrt install) Error flashing / Corrupt firmware

The TFTP commands might vary across different implementations. Here are two examples, netkid's TFTP client and Advanced TFTP (available from: ftp://ftp.mamalinux.com/pub/aTFTP/ or http://freecode.com/projects/atftp , http://pkgs.repoforge.org/atftp/ , http://sourceforge.net/projects/atftp/ ). If you are a debian user, you can install the TFTP-hpa client with apt-get netkit's and TFTP-hpa TFTP commands: TFTP 192.168.1.1 TFTP> binary TFTP> rexmt 1 TFTP> trace Packet tracing on. TFTP> put openwrt-g-code.bin Setting "rexmt 1" will cause the TFTP client to constantly retry to send the file to the given address. As advised above, plug your box after typing the commands, and as soon as WRT54G's bootloader start to listen, your client will successfully connect and send the firmware. You can

try to run # ping -f 192.168.1.1 (as root) in a separate window and fire the line put openwrt-gcode.bin as the colons stop running over your terminal when you power-recycle your Linksys. Advanced TFTP commands: aTFTP TFTP> connect 192.168.1.1 TFTP> mode octet TFTP> trace TFTP> put openwrt-g-code.bin You don't have to tell TFTP to retry file sending, that's default. Note: Dont forget about your firewall settings, if you have one Table 3. TFTP error TFTP error Code pattern is incorrect Invalid Password Timeout reason The firmware image you're uploading was intended for a different model. The firmware has booted and you're connected to a password protected TFTP server contained in the firmware, not the bootloader's TFTP server. Ping to verify the router is online Try a different TFTP client (some are known not to work properly)

If your computer is directly connected to the router and you are consistently getting "Invalid Password" failures, try connecting your computer and the router to a hub or switch. Doing so will keep the link up and prevent the computer from disabling its interface while the router is off. Windows 2000 has a TFTP server, and it can be used to flash with OpenWrt firmware. Note that the Windows PC needs to be configured with a static IP address in the 192.168.1.0/24 subnet, and cannot use a DHCP IP address when flashing the firmware. To learn more please see experimental section below.

4. Using OpenWrt
4.1. Using OpenWrt for the irst time If the upload of the firmware has been running without interruption and your router reboots you can try to log in with telnet. Once booted, you should be able to telnet into the router using the last address it was configured for. Trying 192.168.1.1... Connected to 192.168.1.1. Escape character is '^]'. BusyBox v1.00 (2004.12.24-03:19+0000) Built-in shell (ash) Enter 'help' for a list of built-in commands. _______ ________ __ | |.-----.-----.-----.| | | |.----.| |_ | - || _ | -__| || | | || _|| _| |_______|| __|_____|__|__||________||__| |____| |__| W I R E L E S S F R E E D O M root@OpenWrt:/# The firmware itself is designed to occupy as little space as possible while still providing a reasonably friendly command line interface. With no packages installed, the firmware will simply configure the network interfaces, setup a basic NAT/firewall and load the telnet server and dnsmasq (a combination DNS forwarder and DHCP server).

Why no telnet password? Telnet is an insecure protocol with no encryption; we try to make a point of this insecurity by not enabling a password. If you're in an environment that requires password protection we suggest installing the dropbear SSH server. What if I can't get in? The problem is caused when the jffs2 partition (see below) is detected but unusable, either the result of previous OpenWrt installation or occasionally just caused by a brand new router. Simply boot into Failsafe and run firstboot to reformat the jffs2 partition.

4.2. Firstboot / jffs2. The OpenWrt firmware contains two pieces, a kernel and a read-only filesystem embeded in the firmware known as squashfs. The job of the firstboot script is to make a secondary, writable jffs2 filesystem out of the free space in flash. When OpenWrt boots; it will check for the existence of a jffs2 partition and attempt to boot from that, otherwise it will boot from the squashfs filesystem. The lack of a jffs2 partition will automatically trigger the firstboot script which will run in the background, creating a jffs2 filesystem and populating it with symbolic links to the squashfs filesystem (which is now remounted to the /rom directory). The effect of this is that the root filesystem will suddenly appear to be writable shortly after bootup, this can be verified with the mount command: $ mount /dev/mtdblock/4 on / type jffs2 (rw)

If you do not see this line you may need to run firstboot manually (just type "firstboot"). The firstboot script can also be used to erase all changes to the jffs2 partition, particularly useful when upgrading from previous OpenWrt versions with different filesystem layouts. 4.3. Editing Files. The use of symlinks by the firstboot script saves space on the jffs2 partition, but it does have some interesting side effects such as edititing files. Since all files are by default symlinks to a read-only filesystem, you will not be able to edit files directly -- you'll get a readonly error if you try. Instead you have to delete the symlink and copy the file to the jffs2 partition to be able to edit it. $ rm /etc/ipkg.conf $ cp /rom/etc/ipkg.conf /etc/ipkg.conf $ vim /etc/ipkg.conf 4.4. ipkg The ipkg utility is a lightweight package manager used to download and install OpenWrt packages from the internet. (Linux users familiar with apt-get will recognise the similarities)

Table 4. ipkg update ipkg list ipkg install dropbear ipkg remove dropbear Download a list of packages available View the list of packages Install the dropbear package Remove the dropbear package

More options can be found via ipkg --help. Additional packages can be found through Nico's package tracker: http://nthill.free.fr/openwrt/tracker/ or http://www.ipkg.be/ these packages can be installed using ipkg install http://example.com/package.ipkg or by adding the the source repository to your /etc/ipkg.conf.

5. OpenWrt configuration.
The most of the configuration in OpenWrt is done by setting variables in the NVRAM, even if you are an experienced Linux user, this model of configuration will be quit new to you and you will have to get used to it. You should always be aware of what you are doing when you change your NVRAM variables. But even when you have bricked your router and can't gain access anymore, there is always the failsafe mode (look in troubleshooting). There is still no real web interface for OpenWrt (if you are searching for an openwrt with build in web interface have a look at http://ff-firmware.sourceforge.net/ ). You can find a couple of other open firmwares for the WRT54G and WRT54GS, which come with a build in web interface if OpenWrt is not what you where looking for. But still I believe OpenWrt is the most powerful distro if you want a full working Linux operating system. 5.1. NVRAM NVRAM stands for Non-Volatile RAM, in this case the last 64K of the flash chip used to store various configuration information in a name=value format. Table 5. NVRAM command Command NVRAM show | less NVRAM get boot_wait NVRAM set boot_wait=on NVRAM set lan_ifnames="vlan0 vlan1 vlan2" NVRAM unset foo NVRAM commit Description Display everything in NVRAM Get a specific variable ( in this case boot_wait ) Set a value set multiple values to one param Delete a variable Write changes to the flash chip (otherwise only stored in RAM)

A complete list of NVRAM variables can be found here: http://openwrt.org

5.2. Network configuration. The names of the network interfaces will depend largely on what hardware OpenWrt is run on. WRT54G V1.x LAN=vlan2 WAN=vlan1 WIFI=eth2 WRT54G V2.x/WRT54GS V1.x LAN=vlan0 WAN=vlan1 WIFI=eth1 ASUS WL-500g WAN=eth0 LAN=eth1 WIFI=eth2 (LAN and WIFI are bridged together in br0 by default)

The basic (802.3) network configuration is handled by a series of NVRAM variables: Table 6. NVRAM variables NVRAM Description

[name]_ifname The firmware image you're uploading was intended for a different model. [name]_ifnames Devices to be added to the bridge (only if the above is a bridge) [name]_proto The protocol which will be used to configure an IP static: Manual configuration (see below) DHCP: Perform a DHCP request pppoe: Create a ppp tunnel (requires pppoecd package) [name]_ipaddr ip address (x.x.x.x)

[name]_netmask netmask (x.x.x.x) [name]_gateway Default Gateway (x.x.x.x) [name]_dns DNS server (x.x.x.x)

The command ifup [name] will configure the interface defined by [name]_ifname according to the above variables. As an example, the /etc/init.d/S40network script will automatically run the following commands at boot: $ ifup lan $ ifup wan $ ifup wifi The ifup lan command will bring up the interface specified by lan_ifname. Normally the lan_ifname is set to br0 which will cause it to create the bridge br0 and add the the interfaces from lan_ifnames to the bridge; lan_proto is usually static which means that br0 will have the ip address from lan_ipaddr, and so on for the rest of the variables listed above. It's important to remember that it's the [name]_ifname that specifies the interfaces, the [name] compontent itself has almost no value. This means that if you changed lan_ifname to be the internet port, vlan1, then ifup lan would bring up the internet port, not the lan ports (despite using

the command ifup lan and using the lan_ variables). Also, it means that you can create any [name] variables you want, foo_ifname, foo_proto .... And they would be used by ifup foo. The only [name] with any signfigance is wan, used by the /etc/S45firewall script. The firewall script will NAT traffic through the wan_ifname, blocking connections to wan_ifname. Further information about the variables used can be found at http://openwrt.org/

5.3. Wireless Configuration Although the wifi_* variables can be used to configure the network settings of the wireless interface, the default setting is to include the wireless interface in lan_ifnames and leave the wifi_* variables unset. If you remove the wireless interface from the lan bridge you can use the following settings: Table 7. wifi_ifname wifi_proto wifi_ipaddr The wireless interface (eth1 or eth2 depending on hardware revision) static or DHCP, method used to configure the interface IP address to use if wifi_proto is static

wifi_netmask netmask to use if wifi_proto is static (X.X.X.X notation) Note: There are wl_* and wl0_* variables; the wl_* variables are obsoleted and were replaced by wl0_*.

Table 8. NVRAM Setting wl0_ifname wl0_hwaddr wl0_mode Description Set by wlconf to the name of the ethernet interface (eth1, eth2) Set by wlconf, use il0macaddr to change the mac Either ap, sta or wet for Access Point mode, station mode or wireless ethernet bridge

NVRAM Setting wl0_infra wl0_closed

Description Select operation mode for sta and wet (0=ad-hoc, 1=infrastructure) (0/1) 0: broadcast ssid 1: hide ssid AU = Worldwide, TH = Thailand, IL = Israel, JO = Jordan, CN = China, JP = Japan, US = USA/Canada/New Zealand, DE = Europe, All = All channels (disabled/allow/deny) used to (allow/deny) mac addresses listed in wl0_maclist List of space separated mac addresses to allow/deny according to wl0_macmode. Addresses should be entered with colons, e.g.: 00:02:2D:08:E2:1D Enable / disable the radio (1=enable) Supported 802.11 modes, automatically set by wlconf Attempt these 802.11 modes Set by wlconf to the wireless revision, (4:v1.0 hardware, 7:v2,gs) The channel to use (1-13 worldwide, 1-11 USA/Canada, default 6, 0=auto channel) Set 54g modes (0=Legacy B, 1=auto, 2=G only, 3=B deferred, 4=performance, 5=LRS, 6=afterburner)

wl0_country_code

wl0_macmode

wl0_maclist

wl0_radio wl0_phytypes wl0_phytype wl0_corerev wl0_channel

wl0_gmode wl0_gmode_protection wl0_rateset wl0_plcphdr wl0_rate wl0_frag

all preamble. long: use long or short preamble, *: use short preamble Set rate in 500 Kbps units (0=auto) Set fragmentation threshold (default 2346)

NVRAM Setting wl0_rts wl0_dtim wl0_bcn wl0_frameburst wl0_antdiv wl0_ssid

Description Set RTS threshold (default 2347) Set DTIM period (default 1) Set beacon period (default 100) (on/off) enable/disable frameburst Select antenna (-1=auto, 0=main[near power jack], 1=aux[near reset button], 3=diversity) Set the SSID of the Wrt54g

For WEP: Table 9. wl0_wep wl0_key1 ... wl0_key4 wl0_key on/off (In experimental, use enabled/disabled instead) WEP keys (example: wl0_key1=DEADBEEF12) primary key index: the wl0_key[1234] used (values: 1,2,3,4) 64bit/128bit wep is autodetected by wlconf based on key length. For 64bit use 5/10 chars and for 128bit 13/26 chars len keys

For WDS: Table 10. wl0_lazywds Set lazywds mode - dynamically grant WDS to anyone(1=enable / 0=disable) wl0_wds Space separated list of WDS member MAC addresses (xx:xx:xx:xx:xx:xx notation) NOTE: if you want to use a wrt54gs as a WDS client with wl0_wds set, the wl0_gmode setting must not be in afterburner (6) mode (apparently no linksys speedboost is available for WDS clients). Also, wl0_mode should be set to ap.

5.4. Static Routes Static routes are a bit uglier to maintain, but they are still maintainable. There is only one NVRAM setting for them: static_route. This contains all the static routes to be added upon bootup. The syntax of the static_route NVRAM variable is as follows: static_route=ip:netmask:gatewayip:metric:interface So, for example, to set a static route to 10.1.2.055.255.255.0 via vlan1, use: $ NVRAM set static_route=10.1.2.0:255.255.255.0:0.0.0.0:1:vlan1 This will make 10.1.2.0 directly connected. To route via a router, use: $ NVRAM set static_route=10.1.2.0:255.255.255.0:192.168.1.1:1:vlan1 This will use vlan1 to send packets to 10.1.2.0 via router 192.168.1.1 NOTE: As of the most recent CVS build, all values must be present. The networking script doesn't detect missing values, and will thererfore not create the route if the syntax is incorrect (things missing, etc.).

5.5. Sample network con igurations.


5.5.1. AP mode. (Note: these examples use wrt54g v2.x/wrt54gs v1.x interface names) The default network configuration: (lan+wireless bridged as 192.168.1.1/24, wan as DHCP) lan_ifname=br0 lan_ifnames="vlan0 eth1" lan_proto=static lan_ipaddr=192.168.1.1 lan_netmask=255.255.255.0 wan_ifname=vlan1 wan_proto=DHCP If you just want to use OpenWrt as an access point you can avoid the WAN interface completely: (lan+wireless bridged as 192.168.1.25/24, routed through 192.168.1.1, wan ignored) lan_ifname=br0 lan_ifnames="vlan0 eth1" lan_proto=static lan_ipaddr=192.168.1.25 lan_netmask=255.255.255.0 lan_gateway=192.168.1.1 lan_dns=192.168.1.1 wan_proto=none To separate the LAN from the WIFI: (lan as 192.168.1.25/24, wireless as 192.168.2.25/24, wan as DHCP) lan_ifname=vlan0 lan_proto=static lan_ipaddr=192.168.1.25 lan_netmask=255.255.255.0 wifi_ifname=eth1 wifi_proto=static wifi_ipaddr=192.168.2.25 wifi_netmask=255.255.255.0 wan_ifname=vlan1 wan_proto=DHCP

5.5.2. Client mode. If you want to use your WRT to connect to another AP or computer rather than to use it as an AP, here are the steps to follow: First reverse the firewall. Optionally, if you just want to disable it, you can delete the file /etc/init.d/S45firewall. To reverse it, here is the content you should put in /etc/init.d/S45firewall: #!/bin/sh . /etc/functions.sh WAN=$(NVRAM get wan_ifname) WIFI=$(NVRAM get wifi_ifname) IPT=/usr/sbin/iptables for T in filter nat mangle ; do $IPT -t $T -F $IPT -t $T -X done $IPT -t filter -A INPUT -m state --state INVALID -j DROP $IPT -t filter -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT $IPT -t filter -A INPUT -i $WIFI -j DROP $IPT -t filter -A FORWARD -m state --state INVALID -j DROP $IPT -t filter -A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT $IPT -t filter -A FORWARD -i $WIFI -j DROP $IPT -t filter -A FORWARD -o $WIFI -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clampmss-to-pmtu Optionally, if you want the source IP address of the outgoing traffic to be modified to the ip of the wifi interface, you should also add the following line: $IPT -t nat -A POSTROUTING -o $WIFI -j MASQUERADE This is also known as doing NAT (Network Address Translation), and it's likely your case if you use the WRT to connect to the internet. If you want your outgoing traffic to keep the source IP address unchanged, don't add that line. The next step is breaking down the default bridge between the Wi-Fi interface and the LAN ports. This is done as follows: $ NVRAM set lan_ifname=vlan0 $ NVRAM set wifi_ifname=eth1

NOTE: This is for version 1, if you have a version with different interfaces change vlan0 and eth1 to the right values This is the main command. It changes the WRT's behavior from AP to client, or station ("sta" for short): $ NVRAM set wl0_mode=sta Then configure the interaces normally. For example, assuming the wifi interface uses DHCP and the LAN interface has the static IP address 192.168.1.1: $ NVRAM set lan_proto=static $ NVRAM set lan_ipaddr=192.168.1.1 $ NVRAM set wifi_proto=DHCP You can configure other options if you need to, like wifi_dns or wifi_gateway. We are done with NVRAM, so we commit and reboot the WRT: $ NVRAM commit $ reboot

5.6. Finding and joining networks If you have internet access from the WRT, it's time to install the wl package, that we'll need now. $ ipkg install http://nthill.free.fr/openwrt/ipkg/stable/20041003/wl_0.1-2_mipsel.ipk You can now scan for nearby access points. $ wl scan ; sleep 1 ; wl scanresults f you get an eth error, try $ wl ap 0 This will put it into client mode You should get somethink like this:

SSID: "Wireless" <-----THIS IS THE SSID Mode: Managed RSSI: -93 dBm noise: -93 dBm Channel: 1 <-----HERE WE GOT THE LINK QUALITY, NOISE AND THE CHANNEL BSSID: 00:A0:C5:83:0B:40 Capability: ESS <-----THIS MEAN THE NODE IS IN AP MODE Supported Rates: [ 1(b) 2(b) 5.5(b) 11(b) ] SSID: "2958738608" Mode: Managed RSSI: -94 dBm noise: -94 dBm Channel: 5 BSSID: 00:A0:C5:98:98:B1 Capability: ESS Supported Rates: [ 1(b) 2(b) 5.5(b) 11(b) ] SSID: "3Com" Mode: Managed RSSI: -88 dBm noise: -91 dBm Channel: 6 BSSID: 00:0F:CB:9F:1C:85 Capability: ESS ShortPre ShortSlot Supported Rates: [ 1(b) 2(b) 5.5(b) 11(b) 6 9 12 18 24 36 48 54 ] SSID: "gamehenge" Mode: Managed RSSI: -94 dBm noise: -90 dBm Channel: 6 BSSID: 00:0C:41:CA:65:0B Capability: ESS Pollable WEP <-----THE "WEP" INDICATES THAT THIS NETWORK IS ENCRYPTED Supported Rates: [ 1(b) 2(b) 5.5 11 ] To join a non-encrypted access point you type: $ wl join [ssid] You can tell WRT to join the same SSID each time it boots by setting wl0_ssid: $ NVRAM set wl0_ssid=MyNetwork When you set an interface to DHCP, OpenWRT runs the DHCP client on that interface automatically at boot time. If you want to re-run the client, for example because you joined another ssid, you can reboot (assuming you also set wl0_ssid NVRAM variable), or you can run the uDHCPc command: $ uDHCPc -i eth1 -b

This will ask the network for an IP address over the interface eth1 (wifi in v2), and fork to the background if it gets no replies. The command wl manages the radio, and it's pretty powerful. Among many options (see them here: http://www.it.uc3m.es/~rcuevas/lis/wl_manual.txt ). There are some particulary interesting: wl txpwr: change the transmit power. Accepts a value between 0-255, which I've heard it's in mW, but don't know for sure. It's said that setting a high value here (above 84) will shorten the live of your radio to the point that setting it to 250 will make it last some months. Use this setting at your own risk. wl txant / wl antdiv: this commands will let you choose which antenna will be used to send and receive respectively. This is usually useful if you have replaced an antenna. 0 means main antenna (the one near the power plug) and 1 means the other antenna. wl status: prints the current ssid, signal quality, channel... etc. wl dissasoc: dissasociates from the current ssid wl rate: sets/gets the speed rate. To set it to auto, use -1.

6. Troubleshooting 6.1. Failsafe mode If you've broken one of the startup scripts, firewalled yourself or corrupted the jffs2 partition, you can get back in by using OpenWrt's failsafe mode. To get into failsafe, plug in the router and wait for the DMZ led to light then immediately press and hold the reset button for 2 seconds. If done right the DMZ led will quickly flash 3 times every second. Note: ( /!\ holding the reset button before the DMZ led can reset NVRAM ) When in failsafe, the system will boot using only the files contained within the firmware (the squashfs partition) ignoring any changes made to the jffs2 partition. Additionally, various network settings will be overridden forcing the router to 192.168.1.1. If you want to completely erase the jffs2 partition, removing all packages you can run firstboot. If you want to attempt to fix the jffs2 partition, mount it with the following commands: $ mtd unlock /dev/mtd $ mount -t jffs2 /dev/mtdblock /jffs After the partition is mounted, you can edit the files in /jffs. If you run firstboot with the jffs2 partition mounted, it will not format the partition, but it will overwrite files with symlinks. (Packages will be preserved; changes to scripts will be lost) Note: if you cannot figure out how to put your device into failsafe mode then remember that you can always modify the boot scripts in the source. So if you want to boot failsafe mode, you might edit your buildroot/build_mipsel/root tc/preinit to something like this: #!/bin/sh mount none /proc -t proc mount none /tmp -t ramfs export FAILSAFE=true exec /sbin/init

Build a new image by typing make in the buildroot directory, install the modified firmware and boot the device. This forces your device to boot in FAILSAFE every time. So in order to boot in normal mode, you'll have to undo the changes you've made to the preinit file ASUS WL-500G units seem to respond only on the WAN port when booted in failsafe mode.

6.2. Resetting to defaults If you're having trouble setting up some feature of your router (wireless, lan ports, etc) and for some reason all of the documentation here just isn't working for you, it's sometimes best to start from scratch with a default configuration. Sometimes the various firmwares you try will add conflicting settings to NVRAM that will need to be flushed. Erasing NVRAM ensures there aren't any errant settings confusing your poor confused router. Run this command to restore your NVRAM to defaults: $ mtd erase NVRAM $ reboot This will clear out the NVRAM partition and reboot the router, the bootloader will create a new NVRAM partition with default settings after the reboot. Remember to set boot_wait back on after you reboot your router -- trying to do it before rebooting will just write your old settings (cached in memory) back to the flash. To reset changes you've made to the OpenWRT filesystem, run $ firstboot If firstboot is run while the jffs2 filesystem is mounted (eg. non-failsafe mode) it will skip formatting and only reset changed files to their defaults. (Files are overwritten with symlinks to their original copy in /rom; extra files and packages are left intact) After these two steps, you'll have a router with a pristine unchanged configuration. Everything should work now.

6.3. Recovering from bad firmware If you've followed the instructions and warnings you should have boot_wait set to on. With boot_wait on, each time the router boots you will have roughly 3 seconds to send a new firmware using TFTP. Use a standard TFTP client to send the firmware in binary mode to 192.168.1.1. Due to limitations in the bootloader, this firmware will have to be under 3MB in size.

Experimental OpenWrt Wireless Router


Here is an example of configuring and using a Linksys WRT54GS running OpenWrt as a wireless router for a client link on the Perth-based WAFreeNet: http://www.wafreenet.org/ By following this section, youll be able to connect computers far away (e.g. <400 m) from your access point. WRT54GS running OpenWrt would provide a smaller and more efficient solution than using a Linux router, a wireless card (or AP in client mode), and a network switch, at a similar cost. With Linux on the WRT, it can provide DHCP, DNS, routing, firewall and VPN termination, as well as providing sufficient switch ports to cater for each PC in the house. Note: there never was any intention to use the 802.11g capabilities of the WRT (as it would be connecting to a 802.11b access point), and the two small dipole antennas supplied with the WRT would certainly not suffice for a 400m wireless link.

The WRT54GS The WRT54GS (versions 1.0 to 3.0) is a Linksys wireless router with the following key features:

200MHz MIPS processor 32MB RAM 8MB flash memory 802.11b/g wireless access point built-in 4-port switch WAN/internet port

Note: the WRT54G has similar features, but only has 16MB RAM and 4MB flash memory. Version 4 of the WRT54GS has the same features as listed above, but has half the memory (i.e. 16MB RAM and 4MB flash memory). The version 5 WRT54G and WRT54GS cannot be flashed to OpenWrt (they have less memory, and run a version of VxWorks, rather than Linux).

Note: a 180-degree slotted waveguide mounted on a mast on roof, providing anyone within range access to the WAFreeNet. Some wireless stumbling indicated a 13dBi double biquad antenna inside the friend's house would provide a decent wireless signal to this waveguide.

The Network Environment On the WAFreeNet, we generally use a /30 subnet for each client link, and allocate an apropriately sized subnet for the client network (in this case, a /29 subnet). The WRT would have to providing routing capabilities to route the /29 subnet over the /30 subnet, provide DHCP and DNS to the client network, firewall traffic appropriately, and also provide a VPN termination for all wireless traffic. Obtaining OpenWrt Firmware The OpenWrt firmware is available as a compiled binary, or as source. As recommended on the OpenWrt, download the binary for the latest stable version, referred to White Russian 0.9 and download openwrt-wrt54gs-squashfs.bin: http://downloads.openwrt.org/whiterussian/rc2/bin/

Flashing to OpenWrt Network Connectivity The WRT54GS's default IP address is 192.168.1.1, so configure a PC with a static IP address in the same subnet, such as 192.168.1.2, and connect it to one of the WRT's LAN ports. Before flashing with OpenWrt, apparently the WAN (aka internet) port must be configured with a valid IP address. Configure WAN IP Using the PC, I point a web browser at the web interface for the WRT's Linksys firmware, available at http://192.168.1.1. Default logon details consist of a blank username, and a password of admin. Using the web interface, navigate to Setup -> Basic Setup, and change the type to "Static IP", and configure it with a valid IP address, netmask and default gateway (I used an IP of 10.10.10.10, netmask 255.255.255.0 and gateway 10.10.10.1).

Enable boot_wait The boot_wait variable needs to be set, to cause the WRT to delay the boot process for a few seconds, allowing a new firmware to be installed through the bootloader.

Note: the WRT54GS firmware versions newer than 3.37.2 cannot have the boot_wait variable enabled through the "normal" method of exploiting the ping hack through the web interface. If you have a newer firmware than 3.37.2, you'll need to downgrade the firmware to version 3.37.2 first. The 3.37.2 firmware for the WRT54GS is available on: http://cyberforat.squat.net/openwrt/binary_images/linksys_official The boot_wait variable needs to be set via a "hack" using the ping functionality in the web interface. In the web interface, navigate to the Administration -> Diagnostics page, and hit the Ping button. Enter each of these lines into the "ip address or domain name" text box, and hit "ping" after each entry: ;cp${IFS}*/*/nvram${IFS}/tmp/n ;*/n${IFS}set${IFS}boot_wait=on ;*/n${IFS}commit ;*/n${IFS}show>tmp/ping.log After the last command, a long list of configuration parameters is shown, and it should include boot_wait=on

Uploading New Firmware There is not much information about flashing OpenWrt firmware to a WRT using a Windows PC, with almost all references mentioning Linux TFTP servers only. I have enough Linux boxes at home, but was using my Windows 2000 laptop to initially configure the WRT, and wanted to be able to flash the firmware from it. Windows 2000 and Windows XP come with a TFTP server, and it can be used to flash with OpenWrt firmware. Note that the Windows PC needs to be configured with a static IP address in the 192.168.1.0/24 subnet, and cannot use a DHCP IP address when flashing the firmware. Note that the WRT's IP address while in boot_wait mode is always 192.168.1.1. Note that the Windows TFTP server doesn't support retries (most Linux TFTP servers allow you to configure it to keep retrying to send the firmware image), so you need to get TFTP started at the right time when booting the WRT. Use the following command on a Windows PC: tftp -i 192.168.1.1 PUT openwrt-wrt54gs-squashfs.bin This command needs to be executed from a command prompt, and run this command at exactly

the same time as you apply power to the WRT to start it's boot cycle. The easiest way to determine the timing is to open a command prompt and run the following: ping -w 5 -t 192.168.1.1 And start the upload as soon as the ping starts responding after powering on the WRT. If the flashing is successful, the TFTP server should respond with a message similar to: Transfer successful: 1549312 bytes in 4 seconds, 387328 bytes/sec And the WRT will be rebooted. If TFTP responds with an invalid password error, then you ran the TFTP command too late in the WRT's boot cycle, and have connected to the secure TFTP server in the firmware, rather than the TFTP server in the boot loader, so you'll need to power the WRT off, and try again. If you repeatedly get invalid password errors, the network card in your PC may be reestablishing its link too slowly, so try connecting both the PC and the WRT to each other via a hub or switch.

The First Boot with OpenWrt Boot Status The DMZ LED on the front of the WRT is used by OpenWrt to indicate the boot status. The LED is on while OpenWrt is booting, and is turned off once the boot process is complete. Firstboot Script When your WRT boots for the first time after it's been reflashed with OpenWrt firmware, the firstboot script is automatically run, and will create the jffs2 partition.

Accessing the WRT Telnet Access Once the boot process is complete (and the DMZ LED is off), you should be able to telnet into the WRT on 192.168.1.1. Security Note that the telnet server in OpenWrt does not have any password protection. This has been done to emphasize the insecurity of telnet. You should set an SSH password immediately by running passwd

This will also cause the telnet server to be disabled, and you'll then need to use SSH instead of telnet to access the WRT.

Configuring the WRT Installing Packages OpenWrt uses the ipkg lightweight package manager to download and install OpenWrt packages. Basic syntax for installing packages is: ipkg install [http://website/path/]packagename[.ipkg] OpenWrt packages are available from OpenWrt's whiterussian package repositry. : http://downloads.openwrt.org/whiterussian/packages/

Changing Configuration with nvram Most configurable settings are stored in Non-Volatile RAM (nvram), and their values can be viewed and modified via the use of the nvram command. To view the current configuration, you can use: nvram show | more nvram get keyname Values can be modified using nvram set keyname=value Note that changes are not permament until they are committed to memory. To commit the nvram configuration and reboot, run nvram commit reboot

Configuring OpenWrt as a Routed Wireless Client Introductory Information here we show you how to configure a LinkSys WRT54GS running OpenWrt as a routed wireless client router. But firstly, be sure to have a look at Matt Kemner's guide to turning the Linksys WRT54G / WRT54GS into an AP-client and routing node: http://www.penguincare.com.au/openwrt/docs.txt . It provides a concise overview on how to configure OpenWrt as a client node, and was invaluable.

Configuration Connecting to the WRT Assuming your WRT has just been flashed as explained above with OpenWrt firmware, you'll need to SSH to 192.168.1.1 to configure it. Remove the Firewall The default firewall on OpenWRT provides some basic inbound firewalling and NAT on the WAN interface. We don't want to use NAT, and will be implementing a more appropriate firewall later, so disable the existing firewall by preventing it from being executed: chmod 644 /etc/init.d/S45firewall Set Hostname Optionally, you can also set the hostname of the WRT: nvram set wan_hostname=MyWrt

Network Configuration Setup WAN Port At this point, we configured the WAN port with a valid IP address on our home network, to complete the configuration, and to give the WRT internet access via my network (for installing additional packages). To configure the WAN (vlan1 interface) port, I used the following: nvram set wan_proto=static nvram set wan_ipaddr=10.60.11.151 nvram set wan_netmask=255.255.255.224 And set a default gateway and DNS server:

nvram set wan_gateway=10.60.11.129 nvram set wan_dns=10.60.11.129 Commit the changes, and reboot: nvram commit reboot The WAN port was then connected to my switch, and I could telnet to the WRT on the IP address I had given to the WAN interface. Remove Bridge The default OpenWrt configuration has the wireless interface bridged with the LAN ports. To allow routing and firewalling between these interfaces, the bridge needs to be removed. At the same time, we'll also rename the LAN ports to vlan0: nvram set lan_ifname=vlan0 nvram unset lan_ifnames

Setup LAN Interface Now that the bridge has been removed, the LAN interface (vlan0) can be configured with a static IP address: nvram set lan_proto=static nvram set lan_ipaddr=10.60.68.17 nvram set lan_netmask=255.255.255.248 Setup Wireless Interface Similarly, the wireless interface (eth1) can be configured: nvram set wifi_ifname=eth1 nvram set wifi_proto=static nvram set wifi_ipaddr=10.60.68.234 nvram set wifi_netmask=255.255.255.252 nvram set wifi_gateway=10.60.68.233 nvram set wifi_dns=10.60.68.233 Rather than relying on the WRT to use decide which antenna socket to use, we'll force it to only use the main antenna socket, located next to the power socket (-1=auto, 0=main, 1=aux, 3=diversity): nvram set wl0_antdiv=0 Note that the antenna designations have changed in the various versions of the WRT. For earlier

WRT54G/WRT54GS models, -1=auto, 0=main (next to power socket), 1=aux (next to reset button), 3=diversity. Starting with WRT54G v2.0 and WRT54GS V1.1 these are reversed 0=main (next to reset button) and 1=aux (next to power jack).

Wireless Client Configuration Set Client Mode The wireless mode of the WRT can be set to ap (access point mode), sta (station/client mode), or wet (wireless ethernet bridge, ie, bridged client). As we're using it as a routed client, the mode gets set as follows: nvram set wl0_mode=sta When using sta or wet mode, you also need to specify if ad-hoc or infrastructure/managed mode is being used, with 0 used to specify ad-hoc mode, and 1 for managed mode: nvram set wl0_infra=1 Set the ESSID The ESSID of the wireless network to connect to needs to be specified: nvram set wl0_ssid=SGNet

Save and Reboot Before continuing, commit all changes, and reboot the WRT: nvram commit reboot After the WRT has rebooted, verify that the configuration changes have been successfully applied.

Testing Wireless Connectivity Using iwconfig iwconfig can be used to check the status of your wireless link, by running iwconfig eth1 If a wireless connection has been established by your WRT, the link quality should have a value greater than zero, and the signal and noise should have valid values: eth1 IEEE 802.11-DS ESSID:"SGNet" Mode:Master Frequency:2.437 GHz Access Point: 00:14:BF:94:C1:35 Tx-Power:19 dBm RTS thr=2347 B Fragment thr=2346 B

Using wl An alternative way is to use a useful utility called wl. The wl utility provides more detail than iwconfig. Install wl using ipkg install wl Once installed, you can use wl to list all the wireless networks that are visible to your WRT, using wl scan; sleep 1; wl scanresults Assuming there is at least one wireless network visible, you should see output similar to SSID: "SGNet" Mode: Managed RSSI: -83 dBm noise: -94 dBm Channel: 13 BSSID: 00:0C:F1:96:C9:BD Capability: ESS Supported Rates: [ 1(b) 2(b) 5.5(b) 11(b) ] You can also use wl to join any wireless network, using wl join SGNet

Additional Configuration Package List Assuming your WRT can access the internet, get it to update its ipkg database, and then retrieve a list of the available packages: ipkg update ipkg list

Finalise Network Configuration Once a wireless connection was established, all further administration and configuration was done over the wireless link. Re-configure WAN Port The WAN port wasn't required, and hence was configured for on-site administration, to provide a way to locally access the WRT for configuration, if required. nvram set wan_proto=static nvram set wan_ipaddr=192.168.1.1 nvram set wan_netmask=255.255.255.0 nvram unset wan_gateway nvram unset wan_dns Save and Test These changes must be committed, and the WRT was rebooted to test the new configuration: nvram commit reboot

Configuring DHCP and DNS on OpenWrt now we explain; how to configure DHCP and DNS on a Linksys WRT54GS running OpenWrt. Introductory Information The OpenWrt build includes a dnsmasq: http://cyberforat.squat.net/openwrt/binary_images/linksys_official/ , a lightweight package which provides a caching DNS server and DHCP server. The DHCP server integrates with the DNS server, allowing it resolve hostnames for DHCP-allocated addresses, if desired. A single instance of dnsmasq can be configured to provide different DNS and DHCP services on separate network interfaces. Configuring DNSMasq Edit Configuration File Edit /etc/dnsmasq.conf and change the configuration to suit your environment. I am using dnsmasq to provide DHCP and DNS services to the LAN ports, as well as to the WAN port (which I am using as an administrative interface only, with no routed access to the LAN / WLAN ports for any clients connected to the WAN port). Note that the example below is for a WRT where the bridge has been broken, e.g. the WLAN and LAN ports are not bridged, but have separate IPs, with the WRT routing traffic between them. The contents of /etc/dnsmasq.conf on my WRT is similar to this: # filter what we send upstream domain-needed bogus-priv filterwin2k # allow /etc/hosts and dhcp lookups via *.lan local=/lan/ domain=houwels.sgnet.wafreenet # enable dhcp (start,end,netmask,leasetime) dhcp-authoritative # dhcp range for LAN ports - 10.60.68.16/29 = 10.60.68.17-10.60.68.22 dhcp-range=vlan0,10.60.68.18,10.60.68.22,255.255.255.248,48h # dhcp range for WAN port - 192.168.1.0/24 dhcp-range=vlan1,192.168.1.2,192.168.1.10,255.255.255.0,5m # dhcp lease file dhcp-leasefile=/tmp/dhcp.leases

# use /etc/ethers for static hosts; same format as --dhcp-host # <hwaddr> [<hostname>] <ipaddr> read-ethers # default gateway and dns for LAN ports dhcp-option=vlan0,3,10.60.68.17 dhcp-option=vlan0,6,10.60.68.17 The IP address of the LAN interface on my WRT is 10.60.68.17, so it is used as the default gateway and DNS by all clients connected to the LAN interfaces. Specifying Static DHCP IP Addresses If desired, details for any static DHCP IP addresses are specified in /etc/ethers, in the following format: # desktop xx:xx:xx:xx:xx:xx 10.60.68.18 # laptop xx:xx:xx:xx:xx:xx 10.60.68.19 # another desktop xx:xx:xx:xx:xx:xx 10.60.68.20 Note that you need to specify the actual MAC addresses in /etc/ethers, but I've replaced the MAC addresses with xx:xx:xx:xx:xx:xx in the example above for obvious reasons.

Completing Configuration Edit init script The default init script for dnsmasq contains some code to determine the LAN interface name, as well as the IP address and netmask, and assumes DHCP will only be active on the LAN interface. We don't need these smarts in the init script, as everything is fully defined in the configuration file. Edit the init script /etc/init.d/S60dnsmasq, and replace the contents with #!/bin/sh /usr/sbin/dnsmasq Restart dnsmasq To make the changed configuration take effect, dnsmasq must be restarted. Restart it using the following: killall dnsmasq /etc/init.d/S60dnsmasq Now the configuration can be tested by connecting a client PC to the LAN and WAN ports, and

verify that the client PC can obtain a DHCP IP address, and can communicate with the DNS server.

Scheduling Jobs With cron on OpenWrt here is an overview on how to configure cron on a Linksys WRT54GS running OpenWrt, to enable scheduled jobs to be run. No additional software needs to be installed on OpenWrt, as it already has the crond binary included. Note : OpenWrt whiterussian RC4 and subsequent versions already have cron already preconfigured, so there's no need to follow the instructions on this page (other than maybe creating the /etc/crontab symlink for convenience). Cron entries can be specified by adding cron jobs to /etc/crontabs/root. Configuring crond Create crontab Directory Firstly, create the directory for crontab files: mkdir /etc/crontabs Note that /var/spool/cron/crontabs/ is the default directory that crond will check for configuration. However, anything in /var/ is lost during a reboot, so we'll use another directory to ensure our crontab file persists between reboots. Create crontab File Cronjobs need to be specified in /etc/crontabs/root. For now, just create an empty file: touch /etc/crontabs/root Symbolic Link For ease of use, I create a symbolic link to the crontab file: ln -sf /etc/crontabs/root /etc/crontab This symbolic link is not required by crond, but it allows me to reference the crontab file using /etc/crontab.

Create Init Script Create an init script, /etc/init.d/S60cron, to start the crond daemon at boot time, with the following contents: #!/bin/sh # start crond /usr/sbin/crond -c /etc/crontabs And make the script executable: chmod 755 /etc/init.d/S60cron Manually Start crond The crond daemon can be manually started using: /etc/init.d/S60cron Verify that crond successfully started by checking the syslog using: logread And you should see something similar to this at the end of the logread output: Mar 21 20:29:38 (none) kern.notice crond[687]: crond 2.3.2 dillon, started, log level 8 Restart crond You'll need to restart crond whenever you make changes to the crontab file. This can be achieved using the following: killall crond; /etc/init.d/S60cron This will stop and restart the crond process, causing it to re-read the crontab file as it starts up, ensuring your changes to the crontab file will take effect. Scheduling Jobs With crond Now that you have crond running on OpenWrt, it can be used to perodically run any task that you want. Just add an entry to /etc/crontabs/root for each task that you want periodically executed. For example, if you wanted to run a script every hour, the following would be added to crontab: # run this script every hour 01 * * * * /path/scriptname > /dev/null

You'll then need to restart crond to make this change take effect: killall crond; /etc/init.d/S60cron for more details on the syntax of the crontab file: http://unixhelp.ed.ac.uk/CGI/mancgi?crontab+5 Logging by crond Note that by default, crond will log a message to the syslog every time it executes a scheduled job. For example, if running a time synchronisation task every 10 minutes, syslog (accessible by running logread from a command prompt) will fill up with messages such as this: Dec 22 11:10:01 (none) kern.notice crond[347]: USER root pid 3286 cmd /etc/init.d/S55ntpclient Dec 22 11:20:01 (none) kern.notice crond[347]: USER root pid 3290 cmd /etc/init.d/S55ntpclient Dec 22 11:21:44 (none) syslog.info -- MARK -Dec 22 11:30:01 (none) kern.notice crond[347]: USER root pid 3294 cmd /etc/init.d/S55ntpclient Dec 22 11:40:01 (none) kern.notice crond[347]: USER root pid 3298 cmd /etc/init.d/S55ntpclient The easiest way to stop these from being logged is to configure crond to send all log messages to /dev/null. To do so, edit /etc/init.d/S60cron and change it to: #!/bin/sh # start crond /usr/sbin/crond -c /etc/crontabs -L /dev/null After restarting crond, it will no longer send any log messages to the syslog. Note that this also means that crond will not log any errors to syslog, so be sure to confirm that crond is operating correctly before configuring it to use /dev/null for logging.

Time Synchronization on OpenWrt Now we discuss on how to configure time synchronization on a Linksys WRT54GS running OpenWrt (also referred to as "time synchronization" in some countries). Introductory Information The WRT doesn't contain a hardware clock, so the clock is reset each time the WRT is rebooted. Even setting the clock to the correct time after a reboot isn't sufficient, as I've found the clock drifts a lot over time (upto several minutes per hour). The solution to this is to synchronize the clock when the WRT is rebooted, and then to periodically synchronize it once the WRT is running. Note that you'll need to have cron.com running on your WRT, to be able to create a scheduled task to perform the time synchronization. Time Synchronization Time Zone Prior to performing time synchronization, you should ensure that the time zone is set correctly on your WRT, by checking the value in /etc/TZ. I'm located in Western Australia (which is GMT+8), so I set the time zone using: echo GMT-8 > /etc/TZ Refer to http://www.linuxselfhelp.com/gnu/glibc/html_chapter/libc_21.html#SEC440 for details of the valid values for TZ. Confusingly, the offset in the TZ value specifies the time value you must add to the local time to get a UTC value, so this is positive if the local time zone is west of the Prime Meridian and negative if it is east. As a result, TZ must be set to GMT-8 for a timezone that is GMT+8. Install IPK Package Install the ntpclient package on OpenWrt: ipkg install ntpclient In addition to installing the ntpclient components, this package may also create an init script, /etc/init.d/S55ntpclient, with the following contents: #!/bin/sh /usr/sbin/ntpclient -c 1 -s -h pool.ntp.org & This will cause ntpclient to attempt a once-off time synchronization to http://www.pool.ntp.org at boot time. Additional parameters can also be passed to ntpclient to tell it to periodically

perform a time synchronization with a specified host. Refer to the ntpclient man page: http://doolittle.icarus.com/ntpclient/README for more information on command line options for ntpclient. Usage information is as follows: Usage: ntpclient [-c count] [-d] [-g goodness] -h hostname [-i interval] [-l] [-p port] [-r] [-s] I've found if the initial time synchronization fails (ie, no route to the specified time server or similar), ntpclient will hang, and will never attempt another synchronization. This can typically occur if the time synchronization is being done over a wireless link or a VPN ( see below), which may not yet be up when the init script is run. Because of this issue, I've used a slightly heavy-handed approach, as detailed below.

Modify Init Script The init script, /etc/init.d/S55ntpclient, is modified to the following: #!/bin/sh # kill any existing ntpclient processes # (they can get stuck if no route to target host) /usr/bin/killall ntpclient # do time sync /usr/sbin/ntpclient -l -h 10.60.74.2 -c 1 -s & The init script will now terminate any existing instances of ntpclient, and then attempts to perform a single time synchronization. Be sure to change the IP address to a valid time server on your own private network, or refer to the http://www.pool.ntp.org/ website for a public NTP server near you. The init script will be run when the WRT boots, thus attempting an initial time synchronization. However, we'll also periodically call the init script, just in case the initial synchronization at boot time failed, and to ensure on-going synchronization.

Periodic Time Synchronization Create /etc/crontabs/root with the following contents: # to timesync every 10 minutes */10 * * * * /etc/init.d/S55ntpclient Restart crond to make this change take effect: killall crond; /etc/init.d/S60cron Your WRT's clock should now be synchronized every 10 minutes.

OpenVPN Termination on OpenWrt now you learn; how to configure an OpenVPN client on a Linksys WRT54GS running OpenWrt.

Introductory Information To secure the wireless network link between the WRT client and the remote access point, I chose to setup a VPN tunnel, and route all traffic from the network behind the WRT through this VPN tunnel. OpenVPN: http://openvpn.net/ was chosen, due to the availability of packages for OpenWrt and numerous other platforms, the security it provides, and the flexibility and ease of configuration. I chose to configure my Linux router at the remote end as the OpenVPN server, with the OpenVPN client being the WRT. Note that I'm using pre-shared keys, rather than SSL/TLS, as it simplifies the configuration. As the subnet behind the WRT is houwels.sgnet.wafreenet, and it is connecting to the SGNet router, I prefix all OpenVPN configuration files with the name of the subnet, namely houwels.

Network Addressing The following network addresses are used below: 10.60.68.16/29 10.60.68.17 10.60.68.18-22 10.60.68.232/30 10.60.68.233 10.60.68.234 10.60.68.236/30 10.60.68.237 10.60.68.238 client subnet behind WRT LAN interface of WRT client PCs behind WRT client link between SGNet and WRT virtual interface on SGNet router WLAN interface of WRT VPN link between SGNet and WRT VPN end-point on SGNet router VPN end-point on WRT

Substitute your own network addresses when implementing your own configuration. Install & Configure OpenVPN Server Install OpenVPN Server I'm using an OpenVPN 2.0.5 server on a RedHat 9 Linux box. Refer to the OpenVPN: http://openvpn.net/ documentation for information on installing OpenVPN on RedHat and other Linux distributions. Create Static Key On the Linux router, create a pre-shared static key for the VPN link: openvpn --genkey --secret /etc/openvpn/houwels_static.key Create Configuration File The OpenVPN configuration file (/etc/openvpn/houwels_openvpn.conf) on the SGNet linux router is similar to this: # Use a dynamic tun device. dev tun0 # 10.60.68.237 is our local VPN endpoint (SGNet). # 10.60.68.238 is our remote VPN endpoint (WRT). ifconfig 10.60.68.237 10.60.68.238 # up script will establish routes once the VPN is alive. up ./houwels.up # pre-shared static key secret houwels_static.key # OpenVPN uses UDP port 1194 by default.

# Each OpenVPN tunnel must use a different port number. port 1194 # Downgrade UID and GID to "nobody" after initialization for extra security. user nobody group nobody # use LZO compression. comp-lzo # More reliable detection when a system loses its connection. ping 15 ping-restart 45 ping-timer-rem persist-tun persist-key # Silence the output of replay warnings, which are a common false # alarm on WiFi networks. This option preserves the security of # the replay protection code without the verbosity associated with # warnings about duplicate packets. mute-replay-warnings # Verbosity level. # 0 = quiet, 1 = mostly quiet, 3 = medium output, 9 = verbose verb 3 Create Routing Script OpenVPN can run a script when the VPN link is established. This is useful, as it allows you to add a route through the VPN tunnel. On the SGNet router, I use the following script (/etc/openvpn/houwels.up) to add a route to the subnet behind the WRT (10.60.68.16/29): #!/bin/bash # add route to houwels network via VPN end-point of WRT route add -net 10.60.68.16 netmask 255.255.255.248 gw $5 Note that the houwels.up script must be executable: chmod 755 /etc/openvpn/houwels.up

Start OpenVPN Once configured, start OpenVPN. On my RedHat Linux router, it's simply a matter of running /etc/init.d/openvpn start And OpenVPN will parse each .conf file it finds in /etc/openvpn/, and start an OpenVPN daemon for each. Install Components on OpenWrt Install IPK Packages Firstly; install the OpenVPN package and dependencies. ipkg install openvpn And ipkg will automatically install all required dependencies, including kmod-tun, liblzo, libopenssl, and of course the openvpn package. The liblzo package provides libraries to support lzo compression for OpenVPN, the libssl package provides libraries for SSL encryption used by OpenVPN, and the kmod-tun package provides the TUN/TAP device driver kernel module required by OpenVPN. Create Configuration Files Firstly, create a directory for all OpenVPN configuration files on the WRT: mkdir /etc/openvpn Copy the previously created shared static key (houwels_static.key) from the Linux router into /etc/openvpn on the WRT. Create the configuration file for the OpenVPN link, /etc/openvpn/houwels_openvpn.conf: # Use a dynamic tun device. dev tun # OpenVPN server is the SGNet router. remote 10.60.68.233 # 10.60.68.238 is our local VPN endpoint (WRT). # 10.60.68.237 is our remote VPN endpoint (SGNet). ifconfig 10.60.68.238 10.60.68.237 # up script will establish routes once the VPN is alive. up /etc/openvpn/houwels.up # pre-shared static key secret /etc/openvpn/houwels_static.key

# OpenVPN uses UDP port 1194 by default. # Each OpenVPN tunnel must use a different port number. port 1194 # Downgrade UID and GID to "nobody" after initialization for extra security. user nobody # use LZO compression. comp-lzo # More reliable detection when a system loses its connection. ping 15 ping-restart 45 ping-timer-rem persist-tun persist-key # Verbosity level. # 0 = quiet, 1 = mostly quiet, 3 = medium output, 9 = verbose verb 3 Create a script /etc/openvpn/houwels.up to establish a default route through the VPN once it is active: #!/bin/ash # add default route through VPN tunnel route add -net 0.0.0.0 netmask 0.0.0.0 gw $5 Once again, the houwels.up script must be executable: chmod 755 /etc/openvpn/houwels.up

Using OpenVPN on OpenWrt Start OpenVPN Before OpenVPN can be started, the tun device driver needs to be loaded: insmod tun Note that this module will be automatically loaded by OpenWrt during a reboot, as installation of the OpenVPN ipkg has already created /etc/modules.d/20-tun. Now manually start OpenVPN using: openvpn --daemon --config /etc/openvpn/houwels_openvpn.conf Test the VPN by trying to ping the remote end-point of the VPN tunnel. If it's not working, increase the verbosity level in the configuration file, restart OpenVPN, and monitor the syslog to see why it might be failing to connect (use logread on OpenWrt, and monitor /var/log/messages on the Linux router). Configure OpenVPN to Auto-Start To get OpenVPN to start each time the WRT is rebooted, create /etc/init.d/S65openvpn with the following contents: #!/bin/sh # start the VPN openvpn --daemon --config /etc/openvpn/houwels_openvpn.conf --ifconfig-nowarn And make the script executable: chmod 755 /etc/init.d/S65openvpn

Completing Configuration Firewall Script Note that you'll need to modify the firewall script on the WRT to allow for the VPN tunnel. I modified the firewall to only allow traffic through the VPN tunnel, and block all other nonVPN-ed traffic.

Performance Testing Network Architecture This WRT is connecting to an 802.11b Minitar MNWAPB access point, and hence is restricted to 802.11b 11Mbps speeds. The throughput was measured by using wget to retrieve a 3MB file over the wireless link. Initial tests were performed during setup, when the WRT was physically located close to the Minitar access point, so the WRT was associated to the Minitar with a link rate of 11Mbps. The

tests were repeated once the WRT was installed at the client site, with similar results. Throughput Without VPN Throughput over the wireless link between the WRT and the Minitar was tested at approximately 600 kbytes/sec (ie, typical for an 802.11b wireless link). Throughput With VPN Once the VPN tunnel was established, and all traffic routed through it, the tests were repeated. Throughput dropped to approximately 300 kbytes/sec. the major cause of this slow-down is the CPU in the WRT, as it needs to encrypt and decrypt all the traffic that is passing through the VPN tunnel. This can be observed by monitoring the CPU usage on the WRT while transferring large amounts of traffic through the VPN tunnel - the OpenVPN process consumes 99% of the CPU during this time. The slow-down caused by the VPN tunnel is acceptable in the situation I'm using the WRT. If this isn't the case, the throughput of the VPN tunnel can be increased by moving the VPN termination from the WRT onto a faster device (ie, a Linux router) behind the WRT.

BGP Routing on OpenWrt with Quagga This page contains an overview on how to configure the Quagga BGP daemon on a Linksys WRT54GS wireless router that is running OpenWrt.

Introductory Information On the WAFreeNet: http://wafreenet.org/ , we have been using BGP (Border Gateway Protocol) as our dynamic routing protocol (after initial unsuccessful attempts with OSPF due to stability issues with route flapping). The Quagga Routing Suite: http://quagga.net/ is an opensource software suite, and provides a stable implementation of BGPv4 for UNIX platforms. It consists of a core zebra daemon, and daemons for supporting various routing protocols, including RIP, OSPF and BGP. Any BGP node only needs to be configured with details of its immediate neighboring nodes, and will then start exchanging routes. This means adding a new node to a network only requires BGP configuration on the new node, and its immediate neighbors, and routes to the new node will then propagate through then entire network. Note that Quagga requires reciprocal configuration on a neighboring node, so you'll need to add neighbor configuration details to the nearest Quagga node before it'll start exchanging routes with your WRT. The sample configuration shown below is for the Jandakot: http://www.nodedb.com/australia/wa/perth/view.php?nodeid=2143 node on the WAFreeNet. This node uses a WRT54G running OpenWrt as a router, and the WRT provides routing, dns, dhcp and firewalling services for the node. Jandakot has an uplink to the ArmadaleAP: http://www.nodedb.com/australia/wa/perth/view.php?nodeid=2093 node, and Willetton: http://www.nodedb.com/australia/wa/perth/view.php?nodeid=2122 has a client link to Jandakot. Install Components on OpenWrt Install IPK Packages Install the appropriate Quagga packages on OpenWrt: ipkg install quagga quagga-bgpd Note that this assumes your WRT has internet access, and is able to download the package list to determine where it needs to download the specified packages. If your WRT doesn't have internet access, you'll need to use a browser to view the package list, manually download the specified packages, and transfer them to your WRT and install them.

Create Configuration Files Firstly, create a directory for all Quagga configuration files on the WRT: mkdir /etc/quagga Create a configuration file for the Quagga zebra daemon, /etc/quagga/zebra.conf: hostname jandakot ! define password for bgpd daemon (for connecting to daemon via telnet) password insertpasswordhere ! define enable password for bgpd daemon (for connecting to daemon via telnet) enable password insertpasswordhere ! ! list interfaces interface eth1 interface vlan0 interface vlan1 interface lo ! ! null route to consolidate all subnets in this /24 ip route 10.60.86.0/24 Null0 255 ! line vty The null route allows us to consolidate all routes for the /24 subnet that this router is responsible for, and will cause it to propagate a single route for the entire /24 subnet, rather than multiple routes for the smaller subnets inside 10.60.86.0/24. Create a configuration file for the Quagga bgpd daemon, /etc/quagga/bgpd.conf: hostname jandakot ! define password for bgpd daemon (for connecting to daemon via telnet) password insertpasswordhere ! define enable password for bgpd daemon (for connecting to daemon via telnet) enable password insertpasswordhere ! ! define router's BGP AS router bgp 65086 ! define ID of router - we use IP of the router bgp router-id 10.60.86.1 ! define network address that this router knows about network 10.60.86.0/24 ! ! armadale neighbour neighbor 10.60.74.253 remote-as 65074 neighbor 10.60.74.253 soft-reconfiguration inbound neighbor 10.60.74.253 distribute-list freenet in

neighbor 10.60.74.253 distribute-list freenet out ! ! willetton neighbour neighbor 10.60.84.253 remote-as 65084 neighbor 10.60.84.253 soft-reconfiguration inbound neighbor 10.60.84.253 distribute-list freenet in neighbor 10.60.84.253 distribute-list freenet out ! ! ACLs to stop people from propagating routes to their own private networks access-list freenet permit 10.48.0.0/12 access-list freenet deny any ! line vty exec-timeout 20160 0 As the Jandakot node has links to two other WAFreeNet nodes which also run bgpd, it'll be configured as a neighbor to each of these nodes, allowing it to exchange routes with each neighbor. The IP address specified for each neighbor is that of the remote router's interface that connects to this node, ie, the IP address that the Jandakot WRT will see the bgpd traffic as originating from. The BGP AS number of each neighbor must also be specified. Each of the neighbors must also have reciprocal configuration in their bgpd configuration file for the router you're configuring (ie, the WRT). Modify Init Script The current quagga package for OpenWrt creates an init script, but if using older versions of the quagga package, you'll need to manually create the init script. Edit the init script, /etc/init.d/S49quagga, and edit the following line, removing all daemons except those listed here: DAEMONS="zebra bgpd" Firewall Script Depending on the firewall script on your WRT, you may need to modify it to allow bgpd traffic. Ensure that in and outbound traffic on TCP port 179 is allowed through the firewall. Starting Quagga on OpenWrt Starting Quagga To manually start the zebra and bgpd daemons for the first time, you can either reboot the WRT, or manually run the init script: /etc/init.d/S49quagga start After making changes to bgpd.conf or zebra.conf, you'll need to restart the zebra and bgpd

daemons. A reboot will certainly achieve this, but a quicker way is to terminate the daemons and restart them using the following syntax: /etc/init.d/S49quagga restart Debugging Quagga Verifying BGP Operation If Quagga is configured correctly at both ends, you should see the routing table of the WRT (viewable by running route -n from a command prompt) being populated with routes from its configured neighbour(s). If routes are not showing up in the routing table, further debugging is required. While the Quagga daemons certainly can be configured to write status and debug information to log files, this isn't really a feasible option on a device such as the WRT, with flash memory. Both the zebra and bgpd daemons provide local telnet access for monitoring and debugging. Telnet to BGP Daemon OpenWrt doesn't have a telnet client, and telnet support hasn't been compiled into busybox. Instead, we need to use Netcat, which is included in the standard OpenWrt build. To telnet to the bgpd daemon, run: nc localhost 2605 And you'll be prompted for a password. (If you have the appropriate entries defined in /etc/services, you can also use nc localhost bgpd, and similarly for zebra.) You need to enter the first password that was defined in /etc/quagga/bgpd.conf, and you'll then be rewarded with a prompt. root@JANDAKOT-AP:~# nc localhost 2605 Hello, this is Quagga (version 0.98.4). Copyright 1996-2005 Kunihiro Ishiguro, et al. User Access Verification Password: insertpasswordhere jandakot> To view the status of the bgpd neighbours, run the following: jandakot> show ip bgp summary And you should be rewarded with output similar to this:

BGP router identifier 10.60.86.1, local AS number 65086 6 BGP AS-PATH entries 0 BGP community entries Neighbor V AS MsgRcvd MsgSent TblVer InQ OutQ Up/Down State/PfxRcd 10.60.74.253 4 65074 10525 10232 0 0 0 6d21h24m 4 10.60.84.253 4 65084 10013 10181 0 0 0 6d22h49m 2 Total number of neighbors 2 This output provides details about how long each neighbour has been connected, and how many routes the WRT has received from each neighbour (in this example, 4 routes from the first neighbour, and 2 from the second). The Up/Down status shows the time that that neighbour has been connected. If it shows anything other than a time, it means the bgpd daemon has not successfully connected to that neighbour, so check the bgpd configuration at both ends. To view the BGP routing table, run the following commend in the bgpd telnet session: jandakot> show ip bgp And you should get something similar to this output: BGP table version is 0, local router ID is 10.60.86.1 Status codes: s suppressed, d damped, h history, * valid, > best, i - internal Origin codes: i - IGP, e - EGP, ? - incomplete Network Next Hop Metric LocPrf Weight Path *> 10.60.68.0/24 10.60.74.253 0 65074 65068 i *> 10.60.74.0/24 10.60.74.253 0 0 65074 i *> 10.60.82.0/24 10.60.74.253 0 65074 65082 i *> 10.60.84.0/24 10.60.84.253 0 0 65084 i *> 10.60.86.0/24 0.0.0.0 0 32768 i *> 10.60.113.0/24 10.60.84.253 0 65084 65113 i *> 10.64.0.0/12 10.60.74.253 0 0 65074 i Total number of prefixes 7 This view provides details of each route received via BGP, as well as the path to that route. For example, from the output above, we can see that the route to 10.60.82.0/24 (SouthArmadale) goes via AS65074 (the ArmadaleAP router) and AS65082 (the SouthArmadale router), and the next hop with respect to Jandakot is 10.60.74.253, which is the IP address at the ArmadaleAP end of the ArmadaleAP-Jandakot link. To finish the telnet session, just type exit.

Telnet to Zebra Daemon To telnet to the zebra daemon, run: nc localhost 2601 And you'll be prompted for a password. You need to enter the first password that was defined in /etc/quagga/zebra.conf, and you'll then be rewarded with a prompt. root@JANDAKOT-AP:~# nc localhost 2601 Hello, this is Quagga (version 0.98.4). Copyright 1996-2005 Kunihiro Ishiguro, et al. User Access Verification Password: insertpasswordhere jandakot> To view the status of the routing table, run the following: jandakot> show ip route And you should be rewarded with output similar to this: Codes: K - kernel route, C - connected, S - static, R - RIP, O - OSPF, B - BGP, > - selected route, * - FIB route K>* 0.0.0.0/0 via 10.60.74.253, eth1 B>* 10.60.68.0/24 [20/0] via 10.60.74.253, eth1, 6d21h25m B>* 10.60.74.0/24 [20/0] via 10.60.74.253, eth1, 6d21h25m C>* 10.60.74.252/30 is directly connected, eth1 B>* 10.60.82.0/24 [20/0] via 10.60.74.253, eth1, 6d21h25m B>* 10.60.84.0/24 [20/0] via 10.60.84.253, vlan1, 6d22h50m C>* 10.60.84.252/30 is directly connected, vlan1 S 10.60.86.0/24 [255/0] is directly connected, Null0, bh C>* 10.60.86.0/28 is directly connected, vlan0 C>* 10.60.86.252/30 is directly connected, vlan1 B>* 10.60.113.0/24 [20/0] via 10.60.84.253, vlan1, 6d22h50m B>* 10.64.0.0/12 [20/0] via 10.60.74.253, eth1, 6d21h25m C>* 127.0.0.0/8 is directly connected, lo

This output provides details about each route that currently exists in the WRT's routing table (kernel routes, dynamic routes, static routes, and routes to directly connected networks), and also

provides further details about the source of the route, and how long zebra has known about that route. Use the help command in the bgpd telnet session for more information on available commands, or refer to the Quagga documentation: http://quagga.net/docs.php for more details.

Wireless antenna Boost your Wi-Fi by Tin Can Waveguide Antenna


For 802.11(b or g) Wireless Networks or other 2.4GHz Applications

Tired of weak Wi-Fi signal strength? Looking for an inexpensive way to increase the range of your wireless network? Well there are several methods to boost it up! Easy or hard, cheap or expensive . . . the type of solution depends upon the reason behind the weak strength, but more of it depends upon you on how you tackle it. Tony Northrop famously suggests 10 tips (on Microsofts At Home centre) for improving the Wi-Fi reception. His proposals for extending your wireless range and improving your wireless network speed and performance listed here:

1. Position your wireless router, modem router, or access point in a central location When possible, place your wireless router, wireless modem router (a DSL or cable modem with a built-in wireless router), or wireless access point (WAP) in a central location in your home. If your wireless router, modem router, or access point is against an outside wall of your home, the signal will be weak on the other side of your home. If your router is on the first floor and your PC or laptop is on the second floor, place the router high on a shelf in the room where it is located. Don't worry if you can't move your wireless router, because there are many other ways to improve your connection.

2. Move the router off the floor and away from walls and metal objects (such as metal file cabinets) Metal objects, walls, and floors will interfere with your router's wireless signals. The closer your router is to these obstructions, the more severe the interference, and the weaker your connection will be.

3. Replace your router's antenna The antennas supplied with your router are designed to be omnidirectional, meaning that they broadcast in all directions around the router. If your router is near an outside wall, half of the wireless signals will be sent outside your home, and much of your router's power will be wasted. Most routers don't allow you to increase the power output, but you can make better use of the power. If your routers antenna is removable, you can upgrade to a high-gain antenna that focuses the wireless signals in only one direction. You can even aim the signal in the direction you need it most. Consider a Linksys high-gain antennatheyre powerful and easy to install. http://www.bing.com/shopping/search?q=Linksys%20high-gain%20antenna&FORM=HURE

4. Replace your laptop's wireless PC card-based network adapter Laptops with built-in wireless networking capability typically have excellent antennas and don't need to have their network adapters upgraded. These tips are for laptops that do not have builtin wireless networking. Wireless network signals must be sent both to and from your computer. Sometimes your router can broadcast strongly enough to reach your computer, but your computer can't send signals back to your router. To improve this, replace your laptop's PC card-based wireless network adapter with a USB wireless network adapter that uses an external antenna. In particular, consider a Linksys Wireless-N or Hawking Hi-Gain Wireless-N USB network adapter. These add an external, high-gain antenna to your computer and can significantly extend your wireless range. http://www.bing.com/shopping/search?q=Linksys%20WirelessN%20USB%20network%20adapter&FORM=HURE http://www.bing.com/shopping/search?q=Hawking%20Hi-Gain%20WirelessN%20USB%20network%20adapter&FORM=HURE

5. Add a wireless repeater Wireless repeaters extend your wireless network range without requiring you to add any wiring. Just place the wireless repeater halfway between your wireless router, modem router, or access point and your computer, and you can get an instant boost to your wireless signal strength. Check out the wireless-N repeaters from Linksys, Hawking Hi-Gain, ViewSonic, D-Link, and Buffalo Technology, or shop for a wireless-N repeater: http://www.bing.com/shopping/search?q=wirelessN+repeater&go=&form=QBRE&qs=n&sk=&sc=1-19

6. Change your wireless channel Wireless routers can broadcast on several different channels, similar to the way radio stations use different channels. In the United States and Canada, these channels are 1, 6, and 11. Just as you'll sometimes hear interference on one radio station while another is perfectly clear, sometimes one wireless channel is clearer than others. Try changing your wireless router's channel through your router's configuration page to see if your signal strength improves. You don't need to change your computer's configuration, because it can automatically detect the new channel.

To find your router configuration page, consult this quick reference table, which shows the default addresses for common router manufacturers. If the address is not listed here, read the documentation that came with your router, or visit the manufacturer's webpage.

Router 3Com D-Link Linksys

Address http://192.168.1.1 http://192.168.0.1 http://192.168.1.1

Microsoft http://192.168.2.1 Broadband Netgear Actiontec 7. Reduce wireless interference The most common wireless technology, 802.11g (wireless-G), operates at a frequency of 2.4 gigahertz (GHz). Many cordless phones, microwave ovens, baby monitors, garage door openers, and other wireless electronics also use this frequency. If you use these wireless devices in your home, your computer might not be able to "hear" your router over the noise coming from them. If your network uses wireless-G, you can quiet the noise by avoiding wireless electronics that use the 2.4 GHz frequency. Instead, look for cordless phones and other devices that use the 5.8 GHz or 900 megahertz (MHz) frequencies. Because 802.11n (wireless-N) operates at both 2.4 GHz and the less frequently used 5.0 GHz frequency, you may experience less interference on your network if you use this technology. http://192.168.0.1 http://192.168.0.1

8. Update your firmware or your network adapter driver Router manufacturers regularly make free improvements to their routers. Sometimes, these improvements increase performance. To get the latestfirmware updates for your router, visit your router manufacturer's website. Similarly, network adapter vendors occasionally update the software that Windows uses to communicate with your network adapter, known as the driver. These updates typically improve performance and reliability. To get the driver updates, follow the instructions for your operating system:

Windows 7: http://windows.microsoft.com/en-us/windows7/Update-a-driver-forhardware-that-isnt-working-properly Windows Vista: http://windows.microsoft.com/en-us/windows-vista/Update-a-driverfor-hardware-that-isnt-working-properly

9. Pick equipment from a single vendor Although a Linksys router will work with a D-Link network adapter, you often get better performance if you pick a router and network adapter from the same vendor. Some vendors offer a performance boost of up to twice the performance when you choose their hardware (like their USB wireless network adapters). Linksys has the SpeedBooster technology for its wireless-G devices, and D-Link has the 108G enhancement for its wireless-G devices. These enhancements can be helpful if you have wireless-G devices and you need to transmit over a long distance or you live in an older house (old walls tend to block the signal more than newly built ones do). If speeding up your connection is important to you, consider the next tipupgrading your wireless technology.

10. Upgrade 802.11a, 802.11b, and 802.11g devices to 802.11n Although wireless-G (802.11g) may be the most common type of wireless network, wireless-N (802.11n) is at least twice as fast and it has better range and stability. Wireless-N is backwardcompatible with 802.11a, 802.11b, and 802.11g, so you can still use any existing wireless equipment that you havethough you wont see much improvement in performance until you upgrade your computer or network adapter to wireless-G, too. If you're using wireless-B or wireless-G and you're unhappy with your networks speed and performance, consider replacing your router and network adapters with wireless-N equipment. If you're buying new equipment, definitely choose wireless-N. Linksys Wireless-N routers, for example, are powerful, secure, and simple to set up. So are Linksys Wireless-N USB wireless network adapters: http://www.bing.com/search?q=Linksys+WirelessN+USB+network+adapter&form=DLRDF8&pc=MDDR&src=IE-SearchBox .

Although all the tips seems to be helping in increasing the reception one way or other; one idea seems notably viable for the purpose . . . Replacing the ordinary antenna with a high gain antenna. A tin can waveguide antenna, or Cantenna, may be just the ticket. Yes, this is leading to the famous Tin Can Antenna solution .This design can be built for under $5 U.S. and reuses a food, juice, or other tin can. here are showed some antennas that worked well. So first; you should learn how Cantenna works?

What is a high gain antenna? When talking about radio antennas, the term Gain refers to the Directional Gain of an antenna. A directional gain is the antennas ability depicting its increased signal reception/transmission by receiving/transmitting the signals in a compelled direction.

The figure shows percentage radiation of an ordinary antenna compared to that of a directional antenna (antennas are centered in middle of the plot). The ordinary antenna radiates the supplied power equally in all directions, whereas the directional antenna radiates it more in one specific direction than other (radiation direction is governed by antenna design, plus, no practical antenna can radiate in purely one direction nor perfectly equal in all directions). Reception is affected in equal proportion when switching about the two types. So the bottom line is that directional antennas tend to have greater range since they radiate most of the power in one particular direction, and better reception since the focus on to one direction for receiving the signal as well. But seeing as there cant be any free lunch, this comes with a price; the antenna is directional obviously, and needs alignment for proper operation.

What is a Cantenna? The name Cantenna is derived from Can Antenna. A Cantenna is simply an open-end cylindrical waveguide (waveguide is a hollow metallic tube used to carry high frequency radio waves), constructed from widely available tin cans. The diameter of domestically available cans (which are mostly containers for tinned eatables) supports waveguide propagation at frequencies of order of couple of GHz. Because of its easy construction and optimum operation frequency centered at 2.4 GHz (as used in Wi-Fi wireless networks) it is domestically constructed by armatures for extending range of their wireless connection; sometimes reaching to up to 6-7Km.

Theory behind the Cantenna Cantenna devices function by focusing and strengthening the radio wave receiving area of communication devices such as wireless phones, internet, television and radios as opposed to conventional antennas which receive signals over a broader area with minimal strength. When a radio wave enters the opening of the can it bounces off the can walls until it reaches the receiving wire within the can. This receiving wire sends the information to the communication device with minimal static or interference. The area in which the cantenna can receive the optimum signal is also adjustable, allowing the cantenna to be used in a variety of locations and environments. A cantenna consists of a hollow tube (usually a 40oz can) and a coaxial cable, as shown in Figure below. The can acts as a microwave waveguide by capturing, confining and propagating the radio frequency signal within its metallic walls. The radio frequency is introduced into the can by a protruding conductor of a coaxial cable. The probe can transmit and receive signals from the waveguide.

The frequency that a cantenna can propagate is a function of the diameter of the tube. Cantennas operate as high pass filters since they can only propagate signal above a certain cut-off frequency. In the case our project, we will be using the common wireless networking (WLAN) standard, IEEE 802.11n-2009 which is transmitted at a frequency of 2.4GHz. Cantenna Radius The typical 40oz food can happens to have the correct diameter to excite the transverse electric mode (TE11) which has a frequency band of 2.412-2.462GHz while blocking off the undesirable transverse magnetic mode (TM01). This result is derived from the following equations: Derivation: According to antenna theory for a hollow cylindrical waveguide:

Where is the waveguides cutoff wavelength r is the diameter of the cylindrical waveguide k is the associated eigenvalue for the desired mode (as determined from the Bessel function) Thus, to transmit a TE11 mode

Converting the equation in terms of frequency, thus

Where c is the velocity of light = 3 x 108 m/s Solving for rmin, the minimum desired radius of the waveguide

Thus, to transmit TE11 for 2.4GHz (lower limit of IEEE 802.11n-2009) will be transmitted if
cutoff

Substituting into

min=3.65[Cm]

To exclude the undesirable mode, TM01, we require that


cutoffTE11<

<

cutoffTM01=2.462GHz

For TM01, Solving for rmax, the maximum desired radius of the waveguide, rmax = 4.67cm. This means that the radius of the can should be between 3.65cm and 4.67cm.

Cantenna Length Figure below shows the optimal dimensions of a cantenna based on antenna theory

Functional Dimensions of Cantenna Lo is the wavelength of the Wi-Fi signal in open air or Lo. Thus,
o=

[m]

Lc is the wavelength of the low cut frequency which is a function of on tube diameter only
c=1.706

Lg is standing wavelength inside the tube; it is function of both Lo and Lc


o 2

Which can be solved Lg={ Range of the Cantenna The signal strength of an antenna is known as gain which is in units of decibels (dB). The gain, given as G, can be defined in terms of the geometry of the aperture receiving the signal, in the case the cantenna, and the wavelength of the frequency it is attuned to as shown in equation below where is the aperture efficiency, is the wavelength and d is aperture diameter.
2 2 o

2 c

[m2] =d2

Antenna efficiency may be a result of the following occurrences: 1) Illumination efficiency: How well the cantenna is aligned to receive the signal from the source. 2) Phase error loss: The cantenna losses signal due to a non uniform surface. 3) Spillover loss: The can isnt large enough to consume the receiving signal. 4) Mismatch (VSWR) loss: mismatch in desired signal to be received to the geometry of the can. 5) RF loss: The receiving wire within the cantenna is not properly aligned or positioned causing the signal to bounce blindly within the can without being received. In order to calculate the actual receiving range of the cantenna there are many factors that can be considered (i.e. temperature, weather conditions, reflectivity of the ground, distance of source, power of source, phase variations, etc.) but for simplicity only the height of the source and the wavelength will be used to analyze the cantennas reception range as shown in equation below: Range length [m]=(4 )/

Assume that the average height of a radio tower is 100m and the average height of a cantenna is 3m to allow for convenient adjusting of the cantenna to receive a signal and the wavelength of the 2.4GHz signal is 0.125m. Equation below shows the range length from these assumptions. Range length [m]=(4 )/0.125[m]=9600[m]

This is a good range, compared to the typical range of the 802.11 which is, 250m outdoors.

Cantenna Design

Cantenna Applications: Cantennas, as we all know, are mainly used for extending Wi-Fi radio range over a LOS link (Line Of Sight; yes, directional antennas require a LOS path to work). Additionally they also find applications for Wi-Fi war drivers, free net operators, and system administrators to run WiFi assessment tests. Cantennas are very inexpensive compared to commercially available Wi-Fi repeater units, but are just as good and some people would argue that they are better. Because of the stated advantages, they are employed in the following applications around the globe:

The most important application is in Wi-Fi radio range extension. Rocketers uses them for high altitude telemetry feedback. Boaters use them for internet access at their docks and/or while on water. Military field squads sometimes use Cantennas for carrying wireless backhaul to their bases.

Interestingly, The Castle in France has four Cantennas installed to form a network; since they cant drill into castle walls to run Cat5. Note: CAT5 (also, CAT 5) is an Ethernet network cable standard defined by the Electronic Industries Association and Telecommunications Industry Association (commonly known as EIA/TIA). CAT5 is the fifth generation of twisted pair Ethernet technology and the most popular of all twisted pair cables in use today. CAT5 cable contains four pairs of copper wire. It supports Fast Ethernet speeds (up to 100 Mbps). As with all other types of twisted pair EIA/TIA cabling, CAT5 cable runs are limited to a maximum recommended run length of 100m (328 feet).

Cantenna construction: Cantennas are inherently cheap and relatively easy to build. The necessary parts and general approach to construction are described below:

Tin can (Ideal dimensions are calculated manually or by software) RF connector (type: N-Female) Active element; Short piece of high gauge (thick) copper wire. Pigtail to connect antenna to RF source.

Cans of several diameters, lengths and material are readily available with a domestic household; obviously different dimensions will yield slight difference in radiation patterns and directional gains. The optimum length and diameter for a particular frequency can be calculated using mathematical functions discussed later on. RF (Radio frequency) connectors can be bought from an electronics repair spare part shop. NType connectors are most popular at frequency Wi-Fi operates (2.4GHz). The active element is the part of antenna that actually radiates the waves. For the frequencies we are going to use Cantenna, the wire should ideally be of gauge 12 (which is about 2mm in

diameter, but minor deviations from the size shall not be a problem). With these dimensions, the element can be made using a piece of an ordinary copper wire that can be taken out from a three phase high power cable. Pigtail is radio frequency transmission line; the wire that connects the wireless device to the antenna. Pigtails are readily available at electronic shops dealing in radio equipment (its technical name is RP-SMA cable). Applying some basic laws of antenna theory, the length of the active element is calculated to be 30mm approx for an operating frequency of 2.4GHz. Wavelength for a 2.4GHz signal is 124mm. Fixing the things on:

The figure gives a pretty good explanation for the dimensions of the can and placement of the active element in it. But obviously, we are not going to communicate satellites over it, minor deviations from ideal dimensions of the Can wont make a significant impact. However, the length and placement of the probe are critical factors and may directly affect its performance. Cantenna working:

The following figure will explain why the placement of the active element was so critical. The basic purpose of imposing the tin over the radiator is to direct all the radiation in one direction. In the figure above, the probe radiates the electromagnetic waves spreading away from the source. The waves radiated towards the bottom of the can are reflected back. Because of the

careful placement of the probe, the reflected wave superimposes the wave which naturally got radiated towards the open end of the can; combining the radiated power in one direction. Have the probe not been placed at a quarter wavelength distance from the base, constructive interference would have not occurred, depleting the effective directional gain. Shown below:

Moreover, if the cans length was less than wavelength the wave wouldnt have been precisely directed before been radiated in the open.

Design enhancement: Sometimes a funnel is fabricated at the open end of a Cantenna to produce additional gain. The fabrication leads to another type of antenna yet very similar to the Cantenna, and is better known as cylindrical horn or simply Funnel Antenna. The funnel does not contribute to gain while transmitting but increases the sensitivity of antenna whilst receiving, simply by collecting radiation from larger area.

Attaching the Cantenna to your Wi-Fi device: If you are using a Wi-Fi modem with an external antenna and wish to employ a Cantenna; it is not going to be a problem at all . . . Just detach the supplied antenna and attach a suitably long pigtail connected to the Cantenna the other end. You may treat your router the same way.

And in case you are using a USB modem without an external antenna, you can plant the intact device into the can; same standard for everything else except that the radiating probe is now replaced by the USB modem itself.

The Connector A N-type Female Chassis-mount connector. One side is N-female for connecting the cable from your wireless equipment, and the other side has a small brass stub for soldering on wire.

Nuts & Bolts youll need them just long enough to go through the connector and the can Wire You'll need about 1.25" of 12 guage copper wire. This wire will stick into the brass stub in the Nconnector.

Instructions for building a cantenna 1. Prepare the can: Obtain a clean, empty can (with one end open) of radius of 3.65cm 4.67cm. It might be necessary to remove the lip at the edge of the can so that it does not interfere with reception. Here: r = 3.65cm 2. Mark the position for drill holes: Use a Cantenna Calculator to calculate the dimensions there are several available online. Mark the position for the N connector (at of the waveguide length) with a pencil. Here: LO = 3.1cm 3. Drilling holes for the N connector and bolts: Using a drill (or a nail in combination with a hammer if an electric drill is not available), drill a hole large enough to insert the N-connector and four holes for the securing bolts. The placement of the hole and connect is very important. Its location is derived from above formulas that use the frequency that the antenna will operate at and the can diameter. To make calculating easy for you, there are a few online calculator to figure it out for you: http://www.elepal.fi/antennit/antenna2calc.php http://www.turnpoint.net/wireless/cantennahowto.html

Optionally you can use the software: Cantennator or other appropriate design programs. Enter the diameter of your can above and click on the calculate button. 802.11b and 802.11g WiFi networking equipment operates at a range of frequencies from 2.412 GHz to 2.462 GHz. Ideally, with your can size, the TE11 cut-off frequency should be lower than 2.412 and the TM01 cut-off should be higher than 2.462. It would be good, also, if your can is longer than the 3/4 Guide Wavelength. You want to mark the location on the can where you will put the hole for the connector. The 1/4 Guide Wavelength number tells you how far up from the bottom metal end of the can to put the center of the hole. Open only one end of your can, eat the contents, and give it a good washing. You'll probably want to remove the label too. Use a ruler to measure up from the closed end 1/4 Guide Wavelength and mark the can with a dot. If you've got a drill, select a bit that matches the size of the center of your connector. You may want to start with a small bit and work the hole larger and larger. You could even start with a hammer and nail, then use drill bits. If you don't have a drill, start with a nail hole and use a file to get the hole to the required size. If you're using a bolt on connector, make four more holes for the bolts - you can use the connector as a drilling guide. 4. Soldering the N connector and copper wire: Cut the copper wire such that in total, the length of the connector and the wire is LO = 3.1cm. Solder the wire onto the connector. After cooling, bolt the N connector into the can (to reduce obstructions, keep the bolts inside the can and the nuts on the outside). 5. Connect to WLAN: Connect the cantenna to the computers wireless card using a pig-tail cable. Note: One of end of the cable will have the matching N male connector; the other will connect to the wireless card, as shown in Figure below.

Soldering of Wi-Fi wire with cantenna

complete cantenna

To use your cantenna, you'll need a special cable commonly called a "Pig Tail". The pig tail connects your wireless card or access point to you antenna. One end of the cable will have a "N" Male connector (just right for connecting your cantenna), while the other end will have a connector appropriate to your card or access point.

You'll want to have a wireless NIC or access point with an external antenna connector. Otherwise, you may have to hack into the one you have to hook up the cable. I wouldn't recommend this unless you're good with a soldering iron and electronics. For this reason, it is recommended the Agere Orinoco cards which have a nice antenna connector. Pig Tails can be handmade if you have the right tools, but it's probably easier to get a pre-made one. Fleeman Anderson & Bird: http://www.fab-corp.com Fleeman Anderson & Bird has a "cantenna kit" for sale that includes the connector and pigtail. Choose one of the "cables" links from the menu and look towards the bottom of the list. Hyperlinktech: http://www.hyperlinktech.com Antenna Systems: http://www.antennasystems.com 6. Find the best reception: Cantennas are linearly polarized. Rotate the cantenna until the strongest signal is achieved. Use Kismet (Linux-compatible) or netstumbler to determine the strength of the wireless signal.

Note: This antenna has linear polarization so rotation of the antenna will affect the strength of your signal and experimentally you can gain the strong signal with rotating the can while watching it on your PC to get the best performance. Netstumbler: http://downloads.netstumbler.com/downloads/netstumblerinstaller_0_4_0.exe

JEFA Tech now sells a ready to go connector for your can! It includes the radiator. No soldering required! http://www.jefatech.com/product/cnfbst They also have a complete Cantenna Kit including a USB adapter to plug it directly into your laptop. It is the one pictured below. Here is the link to it on their webpage: http://www.jefatech.com/product/USB-CANTENNA-Kit

A spreadsheet to generate NEC2 models http://www.ivor.it/wireless/index.html#calcs

for

cantennas

can

be

found

here:

Cantenna 14 dBi with built-in 802.11-G USB Wi-Fi adaptor Share Internet signal up to 1.5 miles this Cantenna is an outdoor and indoor antenna designed to reach 2 distant points (computers or network devices) without any RJ-45 wires. You can share the Internet signal up to 1.5 miles by using 2 Cantennas. It has a build-in USB Wi-Fi Adapter which covers 802.11-B and 802.11-G and captures the signal up to 14 dBi. This is the only Cantenna with a built-in USB adaptor on the market. http://www.illumi-nations.com/cantenna-usb-80211-6ft-usb-cable-and-tripod

Note: Cantennas can be used to increase cell phone range, improve reception, and decrease noise while cantennas are useful for extending a wireless local area network (WLAN), the tiny design makes them ideal for mobile applications such as wardriving. The design of the cantenna is so simple that it is often the first antenna Wi-Fi experimenters learn to build. Cantennas may be used with other RF devices such as wireless security cameras.

Technical Specification Reach a distant Internet signal without headache:


A Plug and Play product with a built-in USB 802.11 G Wi-Fi Adaptor No need to buy extra Wi-Fi Card (PCI or PCMCIA Wi-Fi Card) No need of Type N or Pigtail connectors No batteries needed Weatherproof Tuned to get the strongest possible signal No signal loss from USB cord like coaxial cable Portable/li> 14 dBi gain 6 feet USB cable 4" Mini Tripod Extensible USB Cable on demand (with USB repeaters). *See bottom notes Brackets for Standard Camera Tripod Dimensions: 4" x 8" x 5" (W x H x L) Zydas1211b Chipset (known as Athero) Software and drivers included Smaller than the original Cantenna but more efficient Operating Systems: windows 2000,xp,vista

USB cables cant be longer than 16 feet. If you need a longer cable you will require USB repeaters. You can plug up to 3 repeaters together for a total of 48 feet of extension plus the existing 6 feet cable on the Yagi (for a total of 54 feet).

Notice: each 3 dbm you got, twice the distance.1.75 miles connection using this Cantenna.

Cantenna as dish feed As with the USB dongle parabolic, you can use the cantenna design as a feeder for significantly higher gain. Mount the can on the parabolic with the opening of the can pointed at the center of the dish. Use the technique described in the USB dongle antenna example (watching signal strength changes over time) to find the optimum location of the can for the dish you are using. By using a well-built cantenna with a properly tuned parabolic, you can achieve an overall antenna gain of 30dBi or more. As the size of the parabolic increases, so does the potential gain and directivity of the antenna. With very large parabolas, you can achieve significantly higher gain. For example, in 2005, a team of college students successfully established a link from Nevada to Utah in the USA. The link crossed a distance of over 200 kilometers! The wireless enthusiasts used a 3.5 meter satellite dish to establish an 802.11b link that ran at 11Mbps, without using an amplifier. Details about this achievement can be found at http://www.wifishootout.com

Horn The horn antenna derives its name from the characteristic flared appearance.The flared portion can be square, rectangular, cylindrical or conical. The direction of maximum radiation corresponds with the axis of the horn. It is easily fed with a waveguide, but can be fed with a coaxial cable and a proper transition

Horn antennas are commonly used as the active element in a dish antenna.The horn is pointed toward the center of the dish reflector. The use of a horn, rather than a dipole antenna or any other type of antenna, at the focal point of the dish minimizes loss of energy around the edges of the dish reflector. At 2.4 GHz, a simple horn antenna made with a tin can has a gain in the order of 10 - 15 dBi. A cantenna can be used as a satellite dish feed horn. The 5.5 GHz cantenna dimensions are almost perfect in that they make a perfect fit for the standard TV satellite dish. The resulting setup is a low-cost high-quality high-gain antenna. Such setups are widely used in wireless community networks for long-distance Wi-Fi links

2 Watt Wireless Amplifier RadioLabs offers true 2-Watts weatherproof kit complete with a DC injector, AC power adapter for 110 or 220VAC automatic switching. This is the most radical way to increase the distance of your wireless system. This will allow you to increase the power of your wireless card or router from a typical 30 milliwatt transmits output to 2 Watts or more! In addition to increasing the transmit power, the incoming receive signal is also amplified by a separate internal receive circuit. To put this in perspective, 2 Watts at 2.4 GHz and a small parabolic antenna would bounce a signal off the moon or send it thousands of miles into space! Note: These wireless amplifiers are FCC compliant with low gain 802.11 antennas, licensed ham radio operators, military, and export applications. Package Contents The Wi-Fi amplifier package includes the 2- Watt bi-directional 802.11B, G and Super G Booster, DC Power Injector, AC Power Cord and 12V DC Adapter

Deep Dish Cylindrical Parabolic Template

dvantages over other antennas such as the Pringles Can Antenna 1. No Pigtail Required 2. No Modification to AP (No voiding of warranty) 3. No Matching (SWR) Problems 4. No Purchased Parts 5. Trivially Easy Construction 6. Very Low Probability of Error 7. As Good As or BETTER Performance than the Pringles Can Antenna 8. Superior Front to Back/Front to Rear Ratio 9. Improves Wireless LAN Privacy 10. Reduces Interference Basically this antenna is so easy to make, tune, and install before electing to purchase a commercial antenna. I needed a parabolic reflector to eliminate off property coverage. This one can eliminate signal from some areas while enhancing signal in other areas. A six or eight inch version of this

reflector is just perfect for eliminating off site coverage while enhancing signal in poorly "lit" areas. You can make one from a Pringles can, there is little need to get fancy. I designed this reflector to be installed in outdoor enclosures with WAP-11 access points but it is becoming quite popular with people building indoor LAN's and people building very short point-to-point links between homes and offices because of it's performance and easy availability (scissors, tape, cardboard, tin foil and twenty minutes and you are in business). It can easily complete links up to one Km by sitting two WAP-11's in windows at each end of a link with clean line of site. The six inch version of the antenna will give you about 10 to 12 dB of gain over what you have. This equates to approximately 27 to 33 dBm of ERP. That means you wind up with an apparent power in the favored direction between 500 mw and 2 Watts. These numbers depend upon your access point, cards in use, which WiFi gear, etc... etc... That gain has to come from somewhere and it comes from the back side of the reflector, power normally transmitted in that direction is "bounced" forward. Therefore you have more control of where your signal is going when using this reflector. That feature of this antenna can be used to enhance the privacy of your wireless network. Please also note that antenna gain is preferable to amplifier gain because it adds to both transmitted and received power. Usually amplifier gain only increases transmitted signal. It does one little good to increase transmitted signal when the access point is unable to "hear" the weak little PCMCIA card at the other end of the link. This reflector is frequency independent, meaning it will work with any wireless gear on any band. Focal length varies with the size of the dish (but proportionally) therefore the focal point is also shown on the drawing. Positioning of the feed point (focal point) is the most critical aspect of a deep dish parabolic. Errors of 1/4" are unacceptable at these frequencies. It may help to "fiddle" with the positioning as small irregularities (~> 1/4 inch) will move the focal point slightly. If the dipole is not in the focal point, you will lose gain. Parabolic reflectors also lose gain if your finished reflector varies much from the correct curve. This drawing should be accurate enough to be scaled to any reasonable size. The reflector is designed to be fed by a dipole. That is why it is not circular. A dipole is long and cylindrical; the focal point on a circular dish is circular. The focal point on this design is a cylinder. Many access points use dipole(s) as their antenna; the WAP-11 is one such AP. This reflector is the optimal shape for such an antenna. More recent units, such as the WET-11, do NOT use dipoles as their antenna. The reflector is designed to be "square". Meaning you will use a piece of square material to shape the curve. If you need to reduce height for packaging reasons, a shorter antenna will work but you will lose roughly 3 dB for each halving of reflector height. It is also important to try to get the dipole lined up in the center of the reflector. If you don't have a copier, or you want to make a very large scale version, you can make your own graph paper and transfer the curve manually. Brown wrapping paper works fine. You might scale each 1/4" block to be 1" and the final result would be a 24" reflector. Smaller

reflectors around 6 or 8 inches are more practical at home. If your access point has two antennas, just make two reflectors one for each antenna. You can use the image directly, , or you may scale it on a copier, using paint, or manually. You might use the template to make a more rigid cardboard template so that you can check the entire surface of your reflector as you shape it. If you decide to scale the image in Paint be sure to check the little square drawn on the template. Scaling can change the "aspect ratio" of an image and that would create a bad template. So as long as the little square on the template is still square after you re-size the template, you still have a good template. You can also decide to use only a portion of the curve from the template. If you do that you should still use the same focal point that is marked on the template. Front to back ratio is a measurement of how well a directional antenna rejects interference from directions other than the desired direction. This reflector has excellent front to back ratio. Front to back ratio with this antenna depends upon the size of the wire mesh you use to make the antenna. Finer mesh will yield only slightly better gain but will yield much better front to back ratio. Modeling shows the F/B ratio to be better than ~25 dB if you use 1/4" or smaller mesh. My calculated gain figures presume the reflector is 55% efficient. If you use a solid sheet of aluminum or copper as your reflector, your gain figures may be a little bit higher than these. The radiation pattern is narrower in the vertical plane than the horizontal plane. With larger sizes pointing the antenna can require care. Any flat metal surface or screen, even tinfoil taped to cardboard will work. You can build one of these in less than a half an hour using an old shoe box and a roll of tin foil.

How much gain can I expect with this reflector? A: That depends upon many factors. The antenna supplied by the vendor. Usually it is a dipole. Most vendor supplied omnidirectional antennas will work with this reflector. Usually you can't get a look at the vendor supplied antenna without voiding your warranty. The dipole supplied by the vendor may or may not be in the exact center of the plastic/rubber housing. This means that it is best to "tweak" your setup by moving the antenna around in an area about the size of a dime and centered upon the specified "focal point". This tweaking can make a significant difference. The material from which you make the reflector. Solid reflectors of smooth metal are best. Often people make reflectors of cast off tin cans. These work fine but the ridges in the can may cause the reflector to "scatter" the reflection and cause the focal point to be fuzzy. This is more pronounced with smaller reflectors. Screening works well so long as the mesh of the

screen is smaller than 1/4" at 2.4 GHz and 1/8" at 5.8 GHz. At 900 MHz you can use 1/2" mesh screening. A Pringles can may be cut up one side and flattened with a steam iron on low heat to prepare it for use as a reflector. It works just fine. The care with which you make the reflector. This design is sensitive to errors. You should try to keep all measurements within 1/8" at 2.4 GHz and 1/16" at 5.8 GHz. The approximate maximum gains for a few reflectors are shown here: Frequency 900 MHz 2.4 GHz (WiFi 802.11b) 5.8 GHz 6 inch Reflector 6 dBi 12 dBi 16 dBi 9 inch Reflector 7.5 dBi 14 dBi 20 dBi 12 inch Reflector 9 dBi 16 dBi 24 dBi

* THESE NUMBERS ARE APPROXIMATE MAXIMUMS. If you observe these kinds of gains, you got really lucky. This reflector is safe for your hardware and you it is better to use two on access points which have two antennas and it works better.

How much will the range increase with a reflector? That depends upon what your range is to start with. Some people say, "WiFi is a three wall solution." If your current range limit is three walls and you use a six inch reflector, you will likely see another 2 or three walls of range. If your current range is 800 feet and you use a six inch reflector, you will likely see your range increase to 1600 to 2000 feet. There are many factors which affect this range estimation. Strict line-of-sight is the only way one can say with reasonable certainty how much range will improve. Strict line-of-sight, is not just being able to see the remote antenna, but also requires clearance around the path the radio wave takes to travel between the antennas. Generally at shorter ranges (less than half a mile) you can say you have strict line of sight if you can see the other antenna. The indoor range estimation problem is different, and has more to do with what is between the client and the access point and what other reflectors are on the premises. Indoor range estimation is more of an art than a science. Certain substances can be particularly tedious. To name only a few; brick, cinder block, metalized insulation, thick plaster, metal screens, metal foils and mylar used to tint windows, etc. Generally these frequencies will pass through most glass with little problem. Understanding this reflector is easier than understanding MAC filtering or WEP or many of the other weird acronyms associated with 802.11b and it is my hope that many people apply this additional layer of security to their home networks. It is a good way for the health and security of wireless networks.

Adding an amplifier: is not the most desirable behavior because as you increase the range at which your access point can be heard, you also increase the threat of intercept, spoofing, and the sensitivity to interference. With some amplifier units, the transmit signal is amplified but the receive signal is not amplified. In such situations amplification will give you the ability to "talk" further than you can "hear". A directional antenna can increase the "sensitivity" of your access point's "hearing". Can I use this design with other frequencies; say my cellular service, or my 900 Mhz telephone's base station? A: Absolutely! That is why I did NOT design in a dipole to drive the reflector, one of the reasons anyway. You see the driving element, the dipole is frequency dependant but the reflector is NOT frequency dependant. Pretty cool, huh? There is a guy in Australia who was using it with his cellular service, but I think he's moved from it to a Yagi. Yagi-Uda arrays are generally better at lower frequencies. They get hard to make at higher frequencies and parabolics become more efficient in terms of bang for the buck. These reflectors work at any frequency.

Biquad Antenna Construction


Here is the construction of a biquad antenna. The biquad antenna is easy to build, and provides a reliable 11dBi gain, with a fairly wide beamwidth.

Parts Required 123x123mm square section of blank PCB


50mm length of 1/2" copper pipe short length of CNT-400 or LMR-400 low loss coax (~300mm long) 250mm of 2.5mm2 copper wire (approx 1.5mm diameter) N connector

Note that you don't have to use blank PCB for the reflector. You can use any material that's electrically conductive, can be electrically connected to the coax braid, and will reflect microwaves (ie, any metal plate will do fine). Some of people are using CDROM as the reflector, as the foil on it will certainly reflect microwaves.

Reflector Cut a square piece of blank printed circuit board, 123x123mm. Thats recommended a size of 123x123mm if using the biquad as a stand-alone antenna, while 110x110 is optimal if using it as a feed for a large dish and also recommends attaching some lips to two sides of the reflector, to reduce radiation from the rear lobes. Use some steel wool to remove any tarnish and polish it up. Cleaning the copper in this way will make it easier to solder.

Blank printed circuit board Cut a 50mm section of copper pipe, and file both ends smooth. Using some sandpaper and/or some files, polish up the copper pipe (including the inside of the copper pipe, to ensure a good connection with the coax braid).

The dimensions of the copper pipe Cut a notch into one end of the copper pipe, removing approx 2mm from half the circumference.

A short secion of copper pipe, notched at one end Drill a hole in the centre of the blank PCB so that the copper pipe is a tight fit in the hole. I found a reamer to be very useful for enlarging the hole to the correct size.

Making a hole in the centre Insert the copper pipe into the hole, with the notched end on the copper side of the blank PCB. The copper pipe should be protruding approx 16mm through the hole, measured on the copper side of the PCB.

Insert the copper pipe into the reflector Solder the copper pipe to the PCB, to ensure a good physical and electrical connection.

Solder the copper pipe to the PCB Quite a bit of heat is needed, due to the thickness of the copper pipe, and an electrical soldering

iron probably won't be able to deliver sufficent heat. I found a small gas torch works quite well. Making the Element The element is made from a length of copper wire, bent into the appropriate shape. Note that the length of each "side" should be as close to 30.5mm as possible (measured from the centre of the copper wire to the centre of the copper wire), which is a quarter of a wavelength at 2.4GHz .

The shape and dimensions of the element I had some offcuts of electrical power cable lying around, and found that 2.5mm2 power cable had a diameter of approx 1.6mm - a little bigger than the 1.2mm that Trevor Marshall specifies, but didn't think it would make a significant difference to the performance of the biquad.

Recycling power cable offcuts Remove the insulation, measure and cut a 244mm length the copper wire, and straighten it as best as you can.

Straighten the wire Measure the mid-point of the wire, and make a 90 degree bend. The bend should be quite sharp and pronounced.

90 degree bend Measure the midpoints of each half, and make two more 90 degree bends in the wire, so that it looks like that shown in the photo below.

Another two bends Once again, measure the midpoints of each section, and make some more 90 degree bends, resulting in what is shown below.

Bend it some more... Do the same to the other side, resulting in the biquad shape.

Make it symetrical...

Clean up all your bends, and ensure each side of the element is as straight as possible, and as close to 30.5mm as possible. Note that you may need to trim a small amount off each end of the wire to achieve this. Assembly The element must now be attached to the reflector. Note that only the two "ends" of the copper wire are to be attached to the copper pipe - the centre of the copper wire must not touch the copper pipe (hence the notch which was cut into the end of the copper pipe. The copper wire element should be approximately 15mm away from the reflector. Testing antenna performance

while varying the spacing between the copper wire element and the rear reflector indicates that a spacing of approx 15mm provides the lowest SWR.

The element soldered onto the copper pipe Strip approx 30mm of the outer sheath from the end of the coax.

Strip the outer sheath Fold the braid back over the outer sheath, and trim the centre conductor, so that about 4mm is protruding.

Fold the braid back, trim the centre conductor Insert the braid into the copper pipe, so that the end of the centre conductor lines up with the extreme end of the copper pipe, and solder the centre of the element to it, ensuring the centre of the element is not in contact with the copper pipe. Refer to some of the additional photos below for details.

Solder the centre conductor to the element

Note that the feed between the rear reflector and the biquad element needs to be shielded. Using coax to feed the biquad element directly, and positioning the coax inside the copper tube achieves this. Use of bare conductors as a feed between the reflector and biquad element results in a radiating feed, which will have a detrimental effect on the biquad's performance.

you can use a coax crimper to crimp the end of the copper pipe onto the coax. This ensures that the coax would not move inside the copper pipe.

The copper pipe crimped onto the coax

The completed biquad Now terminate the other end of the coax with an N connector. If desired, you can add spacers at each end of the element, to ensure the element doesn't move in relation to the reflector. If you intend to mount the biquad outside, its recommend you place it into a weather-proof enclosure, to prevent corrosion, and to prevent water ingress into the coax. Numerous people have used small tuppaware containers successfully. This can be achieved by drilling a hole in one side of the container, and pass the coax tail through the hole, leaving the biquad itself inside the container. Seal up the hole for the coax with some silicone, and your biquad should be protected against the elements.

Another view of the completed biquad Testing Some very rough initial testing using the biquad as a feed on a 24dBi Conifer dish looks very promising, with the signal strength being at least as as good as my home made Conifer dipole (I was holding the biquad at approximately the focal point of the dish, and hadn't even removed the Conifer dipole). You can also manage to get a marginal link to a 180 degree waveguide on an access point 10km away, using only the biquad by itself, connected to a 30mW RoamAbout wireless card.

Test Equipment We used two laptops, one at either end of our wireless link. The specs for the laptop at the remote end:

Pentium III 1GHz with 128Mb RAM Enterasys RoamAbout wireless card: http://www.enterasys.com/products/items/CSIxDAA/ Windows 2000 SP2 Enterasys 7.44 drivers and client utility: http://www.enterasys.com/software/RoamAbout/RoamAbout-Client-WIN95-98-2000ME-NT-XP-744-pkg.zip running on battery power for the duration of the tests

The specs for the laptop at the antenna end:


Pentium III 700MHz with 256Mb RAM Enterasys RoamAbout wireless card Windows 2000 SP2 Enterasys 7.44 drivers and client utility running on battery power for the duration of the tests

the results indicates this biquad has a gain of approx 11-12dBi. The azimuth plot (ie, radiation pattern) of the biquad is shown below, and shows a 3dB beamwidth of about 50 degrees. The normalised results for each antenna are: horizontal polarisation: gain antenna (dBi) Conifer 22 TM waveguide 17 RC waveguide 19 biquad1 12 biquad2 12 collinear 10 cantenna 13 vertical polarisation: gain antenna (dBi) Conifer 22 TM waveguide 14 RC waveguide 16 biquad1 10 biquad2 8 collinear 8 cantenna 12

Azimuth plot of the biquad Variations

biquad1

biquad2

A number of people have suggested the spacing between the element and the rear reflector should be a 1/4 wavelength (ie, 30.5mm) instead of 15mm. However, test results shows the SWR of the biquad is minimised when the spacing is about 15-17mm. Increasing the spacing to 30.5mm increases the SWR significantly, thus reducing the efficiency of the biquad. Usage When using a biquad to establish a link to another wireless device, you should ensure the polarisation of the biquad is the same as the antenna you are connecting to. Similarily, if establishing a link with two biquads, ensure they are both oriented for the same polarisation. Failing to match the polarisation will result in significant signal loss.

vertically polarised

horizontally polarised

Changing the polarisation is just a matter of rotating the entire biquad antenna by 90 degrees. The biquad antenna is not particularly directional, but has a fairly wide beamwidth. The 3dB beamwidth for a biquad (without side lips) is typically about 40-50 degrees, thus making it ideal for any applications where you want fairly wide coverage.

The relatively wide beamwidth also makes a biquad very suitable for war-driving and stumbling, allowing you to pick up signals without having to align the antenna directly with the signal source. While a directional antenna, such as a Conifer dish (3dB beamwidth of a 24dBi Conifer dish is approx 7 degrees), is better suited for point-to-point links, the narrow beamwidth of a Conifer dish requires more precision when aligning the antennas (the narrower the beamwidth, the less susceptible it will be to interferance from other sources). An antenna with a wider beamwidth, such as a biquad, doesn't require the same precision for alignment, thus making it easier to get a link working.

Low sidelobe 802.11b BiQuad feed for Primestar dish The Primestar dishes are high gain, low cost, parabolic reflectors with an offset feed. They have superior sidelobe performance when compared with a wire grid antenna, reducing the chance that somebody off of the axis of your link will be able to interefere with it. But they are hard to feed because the f/d ratio varies from about 0.5 in the vertical axis to 0.8 on the horizontal axis. Additionally the spacing between the feed 'slot' and the feed mounting bar is small (about 55 mm), which is less than a half wavelength at 2.4GHz Failure to couple efficiently to the dish's wide aperture, or to minimize radiation into the mounting bar, will result in poor gain and/or significant sidelobes. The feed is oriented for vertical polarization in this photo. To make it horizontal merely rotate the feed by 90 degrees. You will lose about 3dB of gain when using the horizontal mode, as the biquad's radiation pattern is a better match for the dish's oblong shape when vertical polarization is used.

Construction of the Biquad I used Printed Circuit board scraps for the 110 x 110 mm reflector, but it will be just as effective if made out of sheet brass or copper. Aluminum can be used if soldering of the rigid coax is not required at the feed point. The reflector's 'lips' are 30 mm high, and serve to reduce coupling into the mounting bar. Note that they are only required along the main edge axis of the reflector. The lips cut down radiation from the rear lobes of the biquad by about 6 dB. The best SWR is obtained when the biquad loop is about 15mm above the ground plane, and the SWR may be adjusted by varying this distance. If you are making a stand-alone antenna, rather than a feed, you will get better gain from a reflector 123 x 123 mm

A piece of 3/4 inch copper piping makes a tight fit with the mount supplied on the Primestar dish The rigid 0.141 diameter coax is soldered to the groundplane to provide physical support for the structure. If the biquad element is constructed carefully there will be no component of radiation along the axis of the coax, no current is induced into the coax outer conductor, and a balun is not needed. An SMA connector can be seen on the end of the rigid coax used to support the biquad element. To make the element take a piece of 1.2mm bare or enamelled copper wire exactly 244 mm long. Bend it in half, and then make the bends at the halfway point on each leg (where the solder joints will be). Then bend the 4 remaining right angles so that the element sides are rectangular, and there is about a 1.5mm gap for soldering to the feed. The widths of the two quad elements will be approximately 30.5mm, from wire center to wire center. You may use standard coax cable to connect at this point, if you do not have rigid cable available, but you will have to figure out how to support the loop physically. The best SWR is obtained when the loop is about 15 mm above the ground plane and when the reflector is mounted about 10mm in front of the Primestar's feed bracket. Kits If you're one of those people who may not have all the tools required for building a biquad antenna from scratch, or you don't want to shop around for all the parts required, you can buy a DIY kit containing all components from WarDrivingWorld: http://wardrivingworld.com Biquad and double biquad antennas, as well as DIY kits for building your own antennas are also available from Biquad Supply. http://biquad.webs.com

Connecting an Antenna Pigtails To connect an external antenna to a wireless radio, an appropriate adapter cable is also required. These cables are typically referred to as "pigtails", and many types are available. Get a short pigtail, as they are typically made from thin coax that has a relatively high attenuation (ie, loss). You will need to get a pigtail with a suitable connector to suit the socket on your wireless radio, and the other connector on the pigtail needs to suit the one on your antenna. If you want to locate the antenna further away from the wireless radio, low-loss coax (such as CFD-400 / CNT-400) is recommended, to ensure you do not lose too much signal in cable losses. Connecting to your Computer The wireless radio also needs to be connected to your computer. This is typically done via an ethernet cable. For example, the UltraWAP shown in the images below has a single ethernet socket on it, allowing it to be connected to a single computer, or to an ethernet switch. The PCMCIA card shown below needs to be plugged into the PCMCIA socket typically found on laptops.

Using a biquad with an UltraWAP wireless AP / bridge The image below shows a biquad antenna connected to the UltraWAP.

Using a biquad with an UltraWAP wireless AP / bridge Another option is to use a PCMCIA wireless card. The image below shows the components required to connect a biquad antenna to a Proxim/Orinoco 802.11b/g wireless PCMCIA card. Many wireless PCMCIA cards use an MCcard socket, and when a cable is plugged into it, the internal antenna in the card is disabled. An MCcard to male N connector pigtail is required to connect the biquad antenna to this particular card.: http://store.freenet-antennas.com.au/product_info.php?products_id=49

Using a biquad with a PCMCIA wireless card The image below shows the biquad antenna connected to the Proxim/Orinoco PCMCIA card.

Using a biquad with a PCMCIA wireless card

Modifying Conifer Antennas for Wireless Networking The most common Conifer antenna used by Galaxy is the 18dBi grid, while the 24dBi grid is a little less common. Note that both the 18dBi and 24dBi grids use an identical feedhorn, so this page is applicable for both.

18dBi and 24dBi ex-Galaxy antennas made by Conifer, with a 30cm ruler (bottom right) for scale However, the Conifer antennas used by Galaxy were designed to operate at a different frequency than wireless networking, and have a down-convertor integrated in the feedhorn. They need to be modified before they can be used for 802.11b wireless networking, and this page describes one way to modify them, achieving very good results. Most of modifying Conifer antennas (ex-Galaxy) show made by cut off the end of the down-converter PCB, and solder coax onto the PCB dipole.

An 18dBi Conifer (as installed by Galaxy)

the most common mod - coax soldered to the cut pcb

Here is a guide of using a brass plate for the dipole. To ensure the correct balun impedance of 50 ohms, the ratio of the inner diameter of the copper tube to the outer diameter of the brass rod should be approx 2.3. The important dimensions are:

length of the dipole is 1/2 wavelength length of the balun is 1/4 wavelength ratio of inner diameter of copper tube to outer diameter of brass rod

The 802.11b standard uses 2.412MHz to 2.484MHz frequency range, so at the centre of that frequency range, 1/2 wavelength is 61mm, and 1/4 wavelength is 30.5mm. Below is a cut-away diagram showing the parts used in the construction of the dipole.

diagram showing components fitted together

Parts Required The materials we used to perform this modification:


Conifer (ex Galaxy) antenna low-loss coax (such as LMR-400 or CNT-400) 50mm of copper pipe (~10mm internal diameter) 61mm of flat brass bar (~12mm wide by ~0.5mm thick) 30.5mm of brass pipe (~4-4.5mm outer diameter) female n-connector

The raw materials: copper pipe, brass tube, brass plate The brass plate is 12mm wide, and 0.6mm thick, while the copper pipe has an internal diameter of 10.8mm, and the brass tube is labelled as "3/16 round brass - stock no 129" with an external diameter of 4.5mm. This means the ratio of the inner diameter of the copper to the outer diameter of the brass is 10.8/4.5=2.4, which is close enough to the required ratio of 2.3.

Antenna Disassembly Start by disassembling your Conifer antenna. Remove the 2 or 4 bolts which attach the mounting bracket and the feedhorn to the dish. Remove the reflector from end of the feedhorn by removing the small screw in the centre of it. Remove the nose cone from the feedhorn. Some people have reported being able to remove the nose cone after cracking the glue with a hammer and screwdriver.

Remove the screw holding the reflector onto the feedhorn

cutting the nose cone

I normally use a hacksaw to cut along the join to remove the nose cone from the feedhorn. Other people have reported carefully squeezing the end of the feedhorn in a vice will crack the glue, allowing the nose cone to be removed.

The feedhorn with the nose cone removed Remove the nut and washer from the base of the feedhorn, and remove the down-convertor from the feedhorn.

Remove the nut & washer at the base of the feedhorn

The down-convertor A hammer may be necessary to persuade the down-convertor to separate from the feedhorn. Separate the metal feedhorn base from the plastic body of the feedhorn, and remove the sticky glue residue using mineral turps.

Remove the sticky glue residue You'll have to drill out the feedhorn base to approx 10-11mm in order to be able to fit the coax through it. Secure the feedhorn base in a bench vice, and carefully enlarge the hole until you can fit your chosen coax through it.

Drilling out the hole in the base A 10mm masonary drill bit at very slow speed works quite well.

Dipole Construction Start by cutting off a 50mm length of copper pipe, and cut some slots in one end, making the length of the slots as close as possible to 30.5mm.

Cutting the slots Clean up the slots with a small needle file (for the car buffs, a points file works quite well too). Clean up both ends of the pipe with a file, and use some sandpaper to clean up the external surface of the copper pipe. Also cleanup the inside of the copper pipe (the cut end, as you'll need to solder it, and the other end to ensure a good connection to the coax braid.

Cleaning up the copper pipe I clean up the pipe by holding it in the chuck of my drill (holding the drill on the workbench), and then using sandpaper and a file on the rotating pipe.

The completed copper pipe with slots Cut off 30.5mm of the small brass tube to make the balun, and clean up the ends with a file. Using a small drill bit, drill a hole near one end of the brass tube. This hole will make it easier to solder the coax core into brass tube.

The hole in the balun For the dipole, we used some brass plate, approx 12mm wide by 61mm long. The length of the brass plate isn't too critical just yet, as long as it's at least 61mm long. It'll be trimmed to the correct length once the parts have been soldered together. Mark the centre of the brass plate, as this is where you'll have to solder the small brass pipe.

Mark the centre Then hold the copper pipe against the brass plate (with the slotted end against the brass plate), and mark its location.

Mark the location of the copper pipe Then hold the copper pipe against the brass plate, and mark its location

Mark the line to cut Now cut the brass plate along the blue line, and clean up the cut ends with a file. I find a junior hacksaw works quite well for this.

The brass plate after being cut Clean up the cut edges, and remove the tarnish with some sandpaper.

The polished brass plate it is possible to use both RG-213 and CNT-400 coax for these modifications, and they require slightly different approaches to the coax core. Note that CNT-400 or LMR-400 is recommended, rather than RG-213, due to the lower impedance. Strip approx 30mm of the black outer sheath off the coax.

RG-213 coax with the outer sheath stripped off Fold the braid back over the remaining outer sheath.

The braid folded back Strip off the central insulation, and if using coax with a stranded core (ie, RG-213), double each strand of the core over, and tighten up the bends with a pair of pliers.

The core folded over Fit the brass tube over the coax core, with the hole previously drilled being located closest to the coax. Solder the brass tube to the coax core, using the hole to supply solder onto the join.

The brass tube soldered onto the coax core Push the copper pipe over the folded-back braid on the coax, until the brass tube protrudes past the end of the copper pipe by at least a few millimetres. Note that you may need to un-braid the coax braid, to as it is a pretty tight fit.

The copper pushed onto the coax Tin the two pieces of the brass plate where they need to be soldered to the brass tube and the copper pipe.

The tinned brass plate Tin the end of the brass tube and the end of the copper pipe with some solder. Solder the brass tube onto the previously marked centre point on the larger of the two brass plate halves.

The brass tube soldered to one half of the dipole

Now slide the copper pipe down against the brass plate, and solder it to the brass plate, ensuring the two slots are aligned against the long sides of the brass plate.

The copper pipe soldered to one half of the dipole Solder the other half of the brass plate to the copper pipe, ensuring there's an air gap of approximately 1mm between the two brass plate sections.

The assembled dipole Measure the overall length of the brass plate, and trim the length to make it 61mm long. This is the dipole, and its length should be as close to 1/2 wavelength as possible. Using the original dipole as a template, measure, mark and drill the the holes in each end of the dipole. These holes are used to locate and hold the dipole in the feedhorn. If you've got access to a coax crimper, use it to crimp the copper pipe onto the coax braid, to ensure a very firm connection, and trim the excess braid which is still protruding past the end of the copper pipe.

Two holes drilled in the dipole, and the copper crimped onto the coax Reassembly The dipole can then be installed into the feedhorn. Use some silocone or hot-melt glue on the ends of the dipole, to ensure it won't become dislogded.

the dipole installed into the feedhorn, and fixed into place with hot-melt glue Glue the feedhorn into the metal base, using a high-strength glue, such as 24hr Araldite.

The feedhorn glued into the base with Araldite Glue the nose cone onto the end of the feedhorn. Re-assemble the antenna, and use silicone or hot-melt glue to seal up the back of the feedhorn (where the coax enters the feedhorn). Terminate the other end of your coax with a female N connector.

Seal the base with silicone

a female N connector

To minimise the stress on the coax where it exits the rear of the feedhorn, use a cable tie to firmly attach it to the antenna mounting bracket, as shown in the photo below. The two U-bolts provide sufficient clearance for the coax between the mast and the bracket, and you can use the existing holes in the bracket.

Coax cable-tied to the bracket The cable tie ensures the coax will not move inside the feedhorn. This is particularly important when using a fairly stiff coax, such as CNT-400. Failure to properly secure the coax in this way can result in the coax moving while you mount the antenna on a mast, and this can lead to broken dipoles. You're now ready to test it! Note that most people using Conifer antennas for wireless networking have them horizontally polarised - that is, they are rotated 90 degrees compared to the way Galaxy mounted them (ie, long axis of the grid is vertical for wireless networking, instead of horizontal).

18dBi modified Conifer mounted for horizontal polarization Note, however, that the polarisation you should use will depend on the polarisation of the antenna you are connecting to. For example, a waveguide is horizontally polarised, while a collinear omni is vertically polarised.

Helical/helix antenna for 2.4 GHz wavelans and/or WiFi applications

The helix antenna, invented in the late fourties by John Kraus (W8JK), can be considered as the genious ultimate simplicity as far as antenna design is concerned. Especially for frequencies in the range 2 - 5 GHz this design is very easy, practical, and, non critical. This contribution describes how to produce a helix antenna for frequencies around 2.4 GHz which can be used for e.g. high speed packet radio (S5PSK, 1.288 Mbit/s), 2.4 GHz wavelans, and, amateur satellite (AO40). Developments in wavelan equipment result in easy possibilities for high speed wireless internet access using the 802.11b (aka WiFi) standard.

Theory The helix antenna can be considered as a spring with N turns with a reflector. The circumference (C) of a turn is approximately one wavelength (l), and, the distance (d) between the turns is approx. 0.25C. The size of the reflector (R) is equal to C or l, and can be a circle or a square. The design yields circular polarization (CP), which can be either 'right hand' or 'left hand' (RHCP or LHCP respectively), depending upon how the helix is wound. To have maximum transfer of energy, both ends of the link must use the same polarization, unless you use a (passive) reflector in the radio path. The gain (G) of the antenna, relative to an isotrope (dBi), can be estimated by: G = 11.8 + 10 * log {(C/l)^2 * N * d} dBi (1) According to Dr. Darrel Emerson (AA7FV) of the National Radio Astronomy Observatory, the results from [1], also known as the 'Kraus formula', is 4 - 5 dB too optimistic. Dr. Ray Cross (WK0O) inserted the results from Emerson in an antenna analysis program called 'ASAP'. The characteristic impedance (Z) of the resulting 'transmission line' empirically seems to be: Z = 140 * (C/l) Ohm (2)

C = 0.75 to 1.33 - circumference of winding S = 0.2126C to 0.2867C - axial length of one turn G = 0.8 to 1.1 - diameter of ground plane / reflector C = D - circumference is pi times the diameter The diameter of the winding is fixed, with the PVC tubing being 42mm in diameter. The centre frequency (2.425GHz) has a wavelength l = 0.123711 metres. C = * 0.042m = 0.13195m = 1.066 Looking back at the measurements, I may have screwed up somewhere because S seems to be 0.31830 C, which is out of range of the specified values. I don't know how this came to be, but it doesn't seem to be too big an impediment. S = 0.3183 * 0.13195m = 0.042m (strangely enough, the diameter of the tubing.) The ground plane diameter G = 1.05 = 0.130m The gain of the aerial in dBi is defined as: Gain = 11.8 + 10*log 10(C * C * n * S) where n is the number of turns. Gain = 11.8 + 10*log 10(1.066 * 1.066 * 13 * 0.31830) = 18.5dBi The chart below shows the amount of gain to be had for the number of turns. As you can see, to get about 3dB (twice) more you have to double the number of turns and double the length of the aerial. Thirteen turns happens to fit into 0.55m and is a good compromise for length versus gain.

A lot of the newer 802.11 cards allow for a selection of centre frequencies (channels). You might want to vary the winding dimensions by using the above formulae to calculate new C and S .

Practical design for 2.43 GHz (aka S-band, ISM band, 13 cm amateur band) l = (0.3/2.43) = 0.1234567 m =12.34 cm (3) The diameter (D) of one turn = (l/pi) = 39.3 mm (4) Standard PVC sewer pipe with an outer diameter of 40 mm is perfect for the job and can be obtained easily from a plumber. The helix will be wound with standard wire used to interconnect 220V AC outlets in house holds. This wire has a colourized PVC isolation and a 1.5 mm thick copper core. Winding it around the PVC pipe will result in D = ca. 42 mm, due to the thickness of the isolation. With D = 42 mm, C = 42*pi = 132 mm (which is 1.07 l) (5) Now d = 0.25C = 0.25*132 = 33 mm (6) For distances ranging from 100 m - 2.5 km with line of sight, 12 turns (N = 12) are sufficient. The length of the PVC pipe therefore will be 40 cm (3.24 l). Turn the wire around the PVC pipe and glue it with PVC glue or any other glue containing tetrahydrofurane (THF). The result will be a very solid helix wound along the pipe, see figure below.

Overview of some of the materials used and dimensions.

The impedance of the antenna, which is: Z = 140 * (C/l) = 140*{(42*pi)/123.4} = 150 Ohm (7) requires a matching network on order to apply standard 50 Ohm UHF/SHF coax and connectors. The use of a 1/4-wave matching stub with impedance (Zs) of: Zs = sqrt (Z1*Z2) = sqrt (50*150) = 87 Ohm (8)

Is very common. Due to the helix design, this equals 1/4 turn. However, from a mechanical point of view bearing water proof aspects in mind when using the antenna outdoors- there are more preferred methods to match the helix to 50 Ohm.

Finished 12 turn 2.4 GHz helix antenna, G = 17.5 dBi or 13.4 dBi (Kraus or Emerson respectively)

Wi-Fi vs WiMAX and BridgeMAXX


Wi-Fi Timeline Wi-Fi is an alliance that certifies wireless devices based on the IEEE (Institute of Electrical and Electronics Engineers) 802.11 standards. IEEE 802.11a and 802.11b are allowing for 54 Mbps in a 5 GHz band and 11 Mbps in a 2.4 GHz band respectively with a range of about 100 feet for 802.11a and up to 350 feet outdoors and 150 feet indoors for 802.11b . 802.11g allows 54 Mbps transmissions in the 2.4 GHz band at ranges of 350 ft outdoors and 150 feet indoors 802.11e in 2005 introduced for quality of service requirements and 802.11i in 2004 for enhanced security. 802.11n for transmission up to 200 Mbps; and 802.11s, added for Mesh Networks. Devices must have WPA (Wi-Fi Protected Access) or WPA2 security and use EAP (Extensible Authentication Protocol). Other option services for Wi-Fi devices include support for 802.11n, security feature set-up, multimedia transfer, power save modes for multimedia, and details about performance in a converged handset and interaction with other Wi-Fi devices. It is based on the IEEE 802.16 standard presented in 2004 and 2005 with data rates as high as 70 Mbps and can reach up to 50 kms. it is also highly mobile whereas Wi-Fi has almost no mobility, and provides excellent security and non-line-of-site services. BridgeMAXX uses towers that cover only a 5 mile radius. Wi-Fi provides coverage of kms, but WiMAX offers a range of tens of kms. WiMAX also offers data rates higher than 802.11a, 802.11b, and 802.11 g, though not as high as the fastest Wi-Fi services of 802.11n ny way it is expensive enough to install.

See: http://www.youtube.com/watch?v=Y7ydkmFaP7E

Wireless network and security recommendations If you have a wireless network, there are some additional security precautions that you should take.

Use a network security key If you have a wireless network, you should set up a network security key, which turns on encryption. With encryption, people can't connect to your network without the security key. Also, any information that's sent across your network is encrypted so that only computers that have the key to decrypt the information can read it. This can help avert attempts to access your network and files without your permission. Wi-Fi Protected Access (WPA or WPA2) is the recommended wireless network encryption method.

Note We recommend using WPA2, if possible. We don't recommend using WEP for network security. WPA or WPA2 are more secure. If you try WPA or WPA2 and they don't work, we recommend that you upgrade your network adapter to one that works with WPA or WPA2.Change the default administrator name and password on your router or access point.If you have a router or access point, you probably used a default name and password to set up the equipment. Most manufacturers use the same default name and password for all of their equipment, which someone could use to access your router or access point without your knowledge. To avoid that risk, change the default administrator user name and password for your router. Check the information that came with your device for instructions about how to change the name and password.

Change the default SSID Routers and access points use a wireless network name known as a service set identifier (SSID). Most manufacturers use the same SSID for all of their routers and access points. We recommend that you change the default SSID to keep your wireless network from overlapping with other wireless networks that might be using the default SSID. It makes it easier for you to identify which wireless network is yours, if there's more than one nearby, because the SSID is typically shown in the list of available networks. Check the information that came with your device for instructions about how to change the default SSID. Position your router or access point carefully Wireless signals can transmit a few hundred feet, so the signal from your network could be broadcast outside of your home. You can help limit the area that your wireless signal reaches by positioning your router or access point close to the center of your home rather than near an outside wall or window

Install a wireless network adapter Most computers have wireless networking built-in. If your computer doesn't have a wireless network adapter, you can install one. The type of adapter you install depends on your computer and your level of expertise.

How to determine if you have a wireless network adapter Before using your computer, check to see if it already has a wireless network adapter.

To find out whether you already have a wireless network adapter 1. 2. 3. 4. Click Start, and then click Control Panel. Click Network and Internet Connections. Under or pick a Control Panel icon, click Network Connections. Microsoft Windows XP displays your network adapters. Wireless network adapters are labeled Wireless Network Connection. If an adapter displays a red X, it is disconnected. If the Network Connections window is blank, your computer doesn't yet have a wired or wireless network adapter.

If you already have a wireless network adapter, you can set up your wireless network.

Tip If your portable computer has a built-in wireless network adapter, but it doesn't appear to be enabled or working, check the back, front, and sides of the computer for a wireless adapter switch. Many laptops include a switch so that you can turn the adapter off to reduce battery consumption.

How to install a wireless USB network adapter Adding a USB wireless network adapter is by far the easiest way to install an adapter.

To install a wireless USB network adapter 1. Before purchasing a wireless USB network adapter, find an available USB port on your computer. Note If you need to move your computer to reach the USB ports, you should shut down Windows to avoid damaging your computer. If you can easily reach a USB port, you do not need to shut down your computer. If you do not have an unused USB port, you can connect a USB hub to add additional ports or install an internal adapter instead. 2. 3. Purchase a wireless USB network adapter. If you had to shut down your computer to get to the USB port, you can now turn on your computer. Insert the CD that comes with the adapter in your computer, and follow the manufacturer's instructions to install the necessary software. If the adapter does not come with a CD, continue to the next step. Connect your USB adapter to the unused USB port on your computer. After a moment, Windows automatically detects and installs the new hardware, and then notifies you when installation is finished. If you are installing a wireless network adapter with a separate antenna, place the antenna in a location where you can get a clear wireless signal. Typically, you will get a stronger signal (and a faster network connection) if you place your antenna away from walls and in a location where it is not blocked by your monitor or computer.

4. 5. 6.

Now you can set up your wireless network.

How to install a wireless CardBus or CF network adapter Many portable computers have either a CardBus or CF card slot (they're the same thing, but the CF card slot is slightly newer and smaller). CardBus and CF cards are more convenient and easier to travel with than USB network adapters for portable computers, because the card fits neatly into a slot on the side of your computer.

To install a wireless CardBus or CF network adapter 1. 2. Purchase a wireless CardBus or CF network adapter. Insert the CD that comes with the adapter in your computer, and follow the manufacturer's instructions to install the necessary software. If the adapter does not come with a CD, continue to the next step. Insert your network adapter into a slot on your computer. After a moment, Windows automatically detects and installs the new hardware, and then notifies you when installation is finished.

3. 4.

Now you can set up your wireless network.

How to install a wireless internal network adapter Internal network adapters are more complicated to install than USB network adapters because they go inside your computer. Also, they can be installed only in desktop computers that have a space (generally called a slot) available. If you are not comfortable opening your computer's case, you can have a technician install the hardware.

To install a wireless internal network adapter 1. 2. If your computer has an available slot, purchase a wireless internal network adapter. Insert the CD that comes with the adapter in your computer, and follow the manufacturer's instructions to install the necessary software. If the adapter does not come with a CD, continue to the next step. On the Start menu, click Turn off Computer, and then click Turn Off. After your computer shuts down, make note of where each cable is connected to the back of your computer. A handy way to do this is to tape a note to each cable with a number or letter on it, and put a matching note next to the spot on your computer where the cable plugs in. Then unplug all cables from your computer.

3. 4.

5.

Lay your computer on a desk, table, or other flat surface. Follow the manufacturer's instructions to open your computer. Depending on the case, you may need to remove screws on the back of your computer. Unlike a watch or TV, most manufacturers design computers so that users can open them up. The slots are located at the back of the computer, typically in the bottom section of the case. Locate an empty slot that fits your card. If necessary, remove the small metal panel covering the opening of the slot, and save the screw. Remove the antenna from the network adapter. Touch an unpainted portion of your computer's case to discharge any static electricity. Then carefully insert the network adapter into the open slot. Gently wiggle the card back and forth until it rests firmly in the slot. Replace the screw that you removed in step 6 to hold the card in place.

6.

7. 8.

9.

10. Attach the antenna to the network adapter 11. Close the computer case. 12. Reconnect all cables to your computer, start your computer, and log on to Windows. After a moment, Windows automatically detects and installs the new hardware, and then notifies you when installation is finished. Now you can set up your wireless network.

Satellites
Signals propagate from the satellites to receptor dishes approximately two by three feet in size mounted by users. Coaxial cable then connects the dish to a modem used to get the data to the user's computer. In a two way system, signals also propagate from a second modem, to the receptor dishes, and back to satellites. In a one way system, a different medium such as wired dial-up is used when the user needs to transmit data. Thus, in a one-way system, the uplink speed is slower, but it is usually the downlink speed that needs to be particularly fast. In general, one way satellite access provides faster, more reliable download access, making it potentially preferable despite the fact that the uplink may tie up phone lines. One way satellite access also lacks Federal Communications Commission regulation. Two-way access typically has about 5000 channels on which data can be transmitted.

In addition to the choice between one-way and two-way satellite communication, there are options about the type of satellites used in the communication. The two main types of satellites are GEOs and LEOs. GEOs, or geosynchronous earth orbit satellites, maintain the same location relative to earth. About 40% of earth can be covered by a single GEO and receptor dishes must have clear line of sight to the location of the satellite. LEOs, or low earth orbit satellites, orbit the earth at an altitude of 450-700 miles. A set of LEOs offers coverage to the entire surface of earth at any given time, though since the satellites constantly change their position relative to earth, the satellite covering a particular location can change by the second. Service providers don't have to pay the cost of establishing base stations for each rural area and so service providers require no additional costs of adding stations that will serve a relatively low number of customers, meaning the financial gain for providing Internet to rural areas via satellite are greater than those of providing Wi-Fi or WiMAX service to rural areas.

Despite the great financial advantage reception dishes require a clear line of sight to the sky without obstructions from things such as trees or bad weather. Tachyon uses a satellite technology called VSAT that uses an antenna with a diameter of 1.8 to 2.4 meters and modem-like device the size of a desktop computer. Tachyon also uses Tachyon Access Points (TAPs) to relay signals to its satellites.

Balloons
I have already discussed using balloon for reconnaissance, intercontinental launching bombs through jet stream and also ozone destructor. For more information search Annafarahmand . And now we explain of using balloons as Mini-Sat Instead of using satellites in space . This improvised Satellite balloon would float up to the edge of space carrying equipment to send and receive wireless Internet or cell phone signals. The equipment could be Wi-Fi based, but would reach customers in a much larger area than traditional Wi-Fi towers. In the most wellknown use of balloons to provide wireless Internet, a balloon carries up the equipment and then once a day, the balloon pops due to the thinner air where it hovers. The equipment drifts back to the ground carried by a parachute. Balloons must be refilled and released again once the equipment reaches the ground.

They share satellites' advantage and cover larger area than wireless towers and do not require as carefully calculated or technical launches like satellites: the balloons are simply filled with hydrogen and released into the air. Anyway you should track down the balloons via GPS (Global Positioning System) and refill and release them. It can be practically hard because of moving balloons by wind. The main company making use of this new balloon technology is Phoenix based Space Data Corporation, owned by Jerry Knoblach. The company provides service to the American southwest by launching 10 balloons per day and has attracted attention from google, which may be interested in investing in Space Data and the services they provide. The balloons Space Data are about 6 feet in diameter and float about 20 miles above the earth's surface. Space Data uses hydrogen instead of helium to fill the balloons because hydrogen is cheaper. The balloons

themselves cost only $50, and the $1500 equipment they carry is protected by Styrofoam casing and the parachutes that carry them back to earth. The equipment weights about six pounds.

Now Space Data provides two versions of their SkySat device: a tethered model, which is limited to around 400 feet and 20 to 30 miles of elevation, and a non-tethered model that can reach heights of more than 65,000 feet and provide a communications range of around 600 miles. Both can be filled with helium or hydrogen.

The balloon climbs about 65,000 feet at the top of the thunderstorm clouds and goes up and provides a very wide area for communication.it is called near-space orbit, which can be defined as the area above airplanes, but below satellites. The balloon, which takes around 60 to 90 minutes to reach altitude can be launched from the back of a truck. Due to its close range to the groundalmost 25 times closer than the nearest satellitethe SkySat can be equipped using the latest consumer technology, such as digital cameras, and be able to provide higher resolution than those found in traditional satellite platforms. Anything you can do with a satellite, you can do with this, without all the weight and complexity of propellers and engines that a big airship has to have. Finally, Data is then erased and the lithium sulfur dioxide battery automatically discharges as the balloon loses altitude, keeping all sensitive information safe from the enemy With balloons you can go out anywhere especially in some of the operating areas we have right now where normal communication methods dont necessarily work long distances

IEEE 802.22 http://en.wikipedia.org/wiki/IEEE_802.22 802.22 provides the potential for long-reaching wireless service, making it ideal for use in the rural community where customers greatly spaced out. Signals from transmitters could extend 40 km or more. The initial drafts of the 802.22 standard specify that the network should operate in a point to multipoint basis (P2MP).

Super Wi-Fi: Instead of using the 2.4 GHz radio frequency of Wi-Fi, the 'Super Wi-Fi' proposal uses the lower-frequency white spaces between television channel frequencies. These lower frequencies allow the signal to travel further and penetrate walls better than the higher frequencies previously used. The FCC's plan is to allow those white space frequencies to be used for free. On January 26th, 2012, the United States first public Super Wi-Fi network was developed in Wilmington, North Carolina. Florida based company Spectrum Bridge; Inc. launched the network for public use with access at Hugh MacRae Park. http://en.wikipedia.org/wiki/White_spaces_%28radio%29 Wi-Fi (except super Wi-Fi) still lacked the range and power needed to make it ideal for serving the rural community. Although Wi-Fi lacked power and range, yet it is still used in Walla Walla County a series of towers each with a 30 mile range were set up to cover 1500 square miles to access internet ranging from 256 kbps to 1.5 Mbps.

Laser Link Laser link technology could help overcome weather-based interference that satellite and balloon technologies face and offers added power to wireless connections spanning the vast distances separating consumers in rural areas. This technology is primarily being developed for the air force as a means of communicating efficiently and quickly from ground to airplanes and satellites through cloud cover, but applications could easily expand to bridging the distances separating rural customers desiring Internet access.

Distributed Systems Distributed systems are an older idea when it comes to providing Internet access to rural communities, and though they could have been useful, they have been replaced with the newer technologies discussed in this paper. One main distributed system used to provide Internet access to rural communities was the Multichannel Multipoint Distributed System, or MMDS. MMDS used microwave frequencies in the range of 2.5GHz to 2.686 GHz and offered a maximum bandwidth of 10 Mb over a range of up to 70 miles. Signals were received via a receive dish placed on the top of a user's home. MMDS was divided into 11 bands within its bandwidth range. When it was newer, MMDS seemed ideal for rural America due to its long range, but line of sight and other issues caused MMDS to become obsolete when the new and improved WiMAX standards were introduced. When it was used, MMDS provided service through companies such as MCI/WorldCom and Sprint. These companies served about 50 million people in both urban and rural areas with MMDS and were able to service over 3000 square miles with one transmitter. MMDS made its way to towns with populations of 6000 or more and to rural areas near larger towns or clusters of towns. As of the release of 802.16in 2004, however, MMDS was pushed aside, and in 2006, frequencies previously allocated to MMDS were reassigned to Advanced Wireless Services through bidding to the FFC. Other distributed systems like LMDS (Local Multipoint Distributed Systems) and the DOCSIS+ (Data over Cable Service Interface Specifications Plus) enhancement to MMDS were also briefly used to provide Internet to many communities, including rural areas, but were eclipsed by the release of 802.16 and WiMAX.

Software-defined radio
A software-defined radio system, or SDR, is a radio communication system where components that have been typically implemented in hardware (e.g. mixers, filters, amplifiers, modulators/demodulators, detectors, etc.) are instead implemented by means of software on a personal computer or embedded computing devices. A basic SDR system may consist of a personal computer equipped with a sound card, or other analog-to-digital converter, preceded by some form of RF front end. Significant amounts of signal processing are handed over to the general-purpose processor, rather than being done in special-purpose hardware. Such a design produces a radio which can receive and transmit widely different radio protocols (sometimes referred to as waveforms) based solely on the software used. Software radios have significant utility for the military and cell phone services, both of which must serve a wide variety of changing radio protocols in real time. A software-defined radio can be flexible enough to avoid the "limited spectrum" assumptions of designers of previous kinds of radios, in one or more ways including:

spread spectrum and ultrawideband techniques allow several transmitters to transmit in the same place on the same frequency with very little interference, typically combined with one or more error detection and correction techniques to fix all the errors caused by that interference. software defined antennas adaptively "lock onto" a directional signal, so that receivers can better reject interference from other directions, allowing it to detect fainter transmissions. cognitive radio techniques: each radio measures the spectrum in use and communicates that information to other cooperating radios, and then transmitters avoid frequencies currently in use by licensed transmitters or are otherwise unusable, and shift transmissions to "empty" frequencies. dynamic transmitter power adjustment, based on information communicated from the receivers, lowering transmit power to the minimum necessary, reducing the near-far problem and reducing interference to others. wireless mesh network where every added radio increases total capacity and reduces the power required at any one node. Each node only transmits loudly enough for the message to hop to the nearest node in that direction, reducing near-far problem and reducing interference to others

Ideal concept The ideal receiver scheme would be to attach an analog-to-digital converter to an antenna. A digital signal processor would read the converter, and then its software would transform the stream of data from the converter to any other form the application requires. An ideal transmitter would be similar. A digital signal processor would generate a stream of numbers. These would be sent to a digital-to-analog converter connected to a radio antenna.

Receiver architecture Most receivers use a variable-frequency oscillator, mixer, and filter to tune the desired signal to a common intermediate frequency orbaseband, where it is then sampled by the analog-to-digital converter. However, in some applications it is not necessary to tune the signal to an intermediate frequency and the radio frequency signal is directly sampled by the analog-to-digital converter (after amplification). Real analog-to-digital converters lack the dynamic range to pick up sub-microvolt, nanowattpower radio signals. Therefore a low-noise amplifier must precede the conversion step and this device introduces its own problems. For example, if spurious signals are present (which is typical), these compete with the desired signals within the amplifier's dynamic range. They may introduce distortion in the desired signals, or may block them completely. The standard solution is to put band-pass filters between the antenna and the amplifier, but these reduce the radio's flexibility - which some see as the whole point of a software radio. Real software radios often have two or three analog channel filters with different bandwidths that are switched in and out.

Applications: The Joint Tactical Radio System (JTRS) is a program of the US military to produce radios that provide flexible and interoperable communications. Examples of radio terminals that require support include hand-held, vehicular, airborne and dismounted radios, as well as base-stations The (JTRS) is planned to be the next-generation voice-and-data radio used by the U.S. military in field operations after 2010. This goal is achieved through the use of SDR systems based on an internationally endorsed open Software Communications Architecture (SCA). This standard uses CORBA on POSIX operating systems to coordinate various software modules. The JTRS radio is to be a telephone, computer and router in one box that can transmit from 2 MHz to 2 GHz. The SCA, despite its military origin, is under evaluation by commercial radio vendors for applicability in their domains. The adoption of general purpose SDR frameworks outside of military, intelligence, experimental and amateur uses, however, is inherently retarded by the fact that civilian users can more easily settle with a fixed architecture, optimized for a specific

function, and as such more economical in mass market applications. Still, software defined radio's inherent flexibility can yield substantial benefits in the longer run, once the fixed costs of implementing it have gone down enough to overtake the cost of iterated redesign of purpose built systems. This then explains the increasing commercial interest in the technology.

Amateur or home use More recently, the GNU Radio (see related sction) using primarily the Universal Software Radio Peripheral (USRP) uses a USB 2.0 interface, an FPGA, and a high-speed set of analog-to-digital and digital-to-analog converters, combined with reconfigurable free software. Its sampling and synthesis bandwidth is a thousand times that of PC sound cards, which enables wideband operation. The HPSDR (High Performance Software Defined Radio) project uses a 16-bit 135 MSPS analog-to-digital converter that provides performance over the range 0 to 55 MHz comparable to that of a conventional analogue HF radio. The receiver will also operate in the VHF and UHF range using either mixer image or alias responses. Interface to a PC is provided by a USB 2.0 interface though Ethernet could be used as well. The project is modular and comprises a backplane onto which other boards plug in. This allows experimentation with new techniques and devices without the need to replace the entire set of boards. An exciter provides 1/2 W of RF over the same range or into the VHF and UHF range using image or alias outputs

Tactical Common Data Link


Fixed lines of communication are vulnerable to enemy attack; communication networks must be mobile and flexible to allow forces to share information on the move. To achieve the information dominance called for in Joint Vision 2020, wideband data must be exchanged rapidly and accurately through battlefield networks to allow friendly forces to quickly assess and effectively respond to threats. TCDL is designed and specified to be common data link (CDL) -compliant to provide interoperability with other DoD and NATO CDL systems. A TCDL system consists of an airborne data terminal and a ground or surface data terminal .TCDL has demonstrated high data rate point-to-point communication at 10.71 Mbps with a range as far as 300 miles

References and Authors 1. OpenWrt website: http://www.openwrt.org/ 2. Quagga Routing Suite: http://quagga.net/ 3. RFC 1771 - A Border Gateway Protocol 4 (BGP-4): http://www.faqs.org/rfcs/rfc1771.html 4. Border Gateway Protocol on Wikipedia: http://en.wikipedia.org/wiki/Border_Gateway_Protocol 5. Matt Kemner's OpenWrt guide: http://www.penguincare.com.au/openwrt/docs.txt 6. Getting secure WLAN by using OpenVPN on a WRT54G under OpenWRT: http://p3f.gmxhome.de/OpenWRT/Configure-OpenVPN.html 7. OpenVPN tls-server running under OpenWRT on a WRT54G (V1.1): http://p3f.gmxhome.de/OpenWRT/Creating-OpenVPN.html 8. http://home.x-pec.com/~ivc/sites/ivc/wrt54g/ 9. http://martybugs.net/wireless/openwrt 10. Martin: Interested in electronics and computers at a young age, he went on to complete a five year combined Science/Engineering degree at the University of Western Australia, majoring in Computer Science and Electrical/Electronic Engineering (honours). mpot@martybugs.net and axis@ii.net : http://martybugs.net http://wafreenet.org/ 11. Morris Winkler: expertized in electronic and wireless networking and he is also a n active member of https://riseup.net : tat@riseup.net 12. Canadas International Development Research Centre, http://www.idrc.ca/. 13. http://networktheworld.org/ 14. http://www.nsrc.org/ 15. Hacker Friendly LLC, http://hackerfriendly.com/ 16. http://opensource.telkomspeedy.com/wiki/index.php/WNDW 17. http://www.radio-electronics.com 18. http://www.radartutorial.eu/18.explanations/ex44.en.html

19.http://apps1.eere.energy.gov/buildings/tools_directory/software.cfm/ID=45/pagename_subme nu=energy_simulation/pagename_menu=whole_building_analysis/pagename=subjects 20. Jason Hecker: http://helix.air.net.au/helix/index.php/d.i.y.-2.4ghz-helical-antenna/ 21. Dr. Remco den Besten: helix@remco.tk 22. Jessica Codr: jmc5@cec.wustl.edu 23. Dr. Raj Jain: jain@cse.wustl.edu 24. Sebastian Bttrich (http://wire.less.dk/) is a generalist in technology with a background in scientific programming and physics. Originally from Berlin, Germany, he worked with IconMedialab in Copenhagen from 1997 until 2002. He holds a Ph.D. in quantum physics from the Technical University of Berlin. His physics background includes fields like RF and microwave spectroscopy, photovoltaic systems, and advanced maths. 25. Laura M. Drewett is a Co-Founder of Adapted Consulting Inc., a social enterprise that specializes in adapting technology. An expert in sustainability for ICT projects 26. Alberto Escudero-Pascual and Louise Berthilson are the founders of IT+46, a Swedish consultancy company with focus on information technology in developing regions. http://www.it46.se 27. Carlo Fonda is a member of the Radio Communications Unit at the Abdus Salam International Center for Theoretical Physics in Trieste, Italy. 28. Jim Forster has spent his career in software development, mostly working on operating systems and networking in product companies. He has experience with several failed startup companies in Silicon Valley, and one successful one, Cisco Systems. 29. Ian Howard: He is now a consultant on various Geekcorps programs. 30. Kyle Johnston, http://www.schoolnet.na/ 31. Tomas Krag spends his days working with wire.less.dk, a registered nonprofit, based in Copenhagen, which he founded with his friend and colleague Sebastian Bttrich in early 2002. wire.less.dk specialises in community wireless networking solutions,Tomas is also an associate of the Tactical Technology Collective http://www.tacticaltech.org/, an Amsterdam-based nonprofit to strengthen social technology movements and networks. 32. Gina Kupfermann is graduate engineer in energy management and holds a degree in engineering and business 33. Adam Messer. Originally trained as an insect scientist, Adam Messer metamorphosed into a telecommunications professional after a chance conversation in 1995 led him to start one of Africa's first ISPs.

34. Juergen Neumann (http://www.ergomedia.de/) started working with information technology in 1984 and since then has been looking for ways to deploy ICT in useful ways for organizations and society. 35. Ermanno Pietrosemoli has been involved in planning and building computer networks for the last twenty years. As president of the Latin American Networking School, Escuela Latinoamericana de Redes EsLaRed, www.eslared.org.ve , he has been teaching wireless data communications in several countries while keeping his base at Mrida, Venezuela. 36. Frdric Renet is a co-founder of Technical Solutions at Adapted Consulting, Inc. Frdric has been involved in ICT for more than 10 years and has worked with computers since his childhood. He began his ICT career in the early 1990s with a bulletin board system (BBS) on an analog modem and has since continued to create systems that enhance communication. Most recently, Frdric spent more than a year at IESC/Geekcorps Mali as a consultant. In this capacity, he designed many innovative solutions for FM radio broadcasting, school computer labs and lighting systems for rural communities. 37. Marco Zennaro, aka marcusgennaroz, is an electronic engineer working at the ICTP in Trieste, Italy. He has been using BBSes and ham radios since he was a teenager, and he is happy to have merged the two together working in the field of wireless networking. He still carries his Apple Newton. 38. Anna farahmand: shes worked for about ten years in aerospace industries and and is experineced on eneregetic material and improvised science and technology. She is now working in the field of information technology, improvised wireless and secure O.S 39. Christopher Ager: christopher.a.ager@baesystems.com 40. http://kioan.users.uth.gr/wireless/cantenna 41. http://martybugs.net/wireless/biquad/ 42. http://www.trevormarshall.com/biquad.htm 43. http://www.usbwifi.orconhosting.net.nz/ 44. http://www.turnpoint.net/wireless/cantennahowto.html 45. http://antenna-diy.blogspot.se

PirateBox
Source: http://wiki.daviddarts.com/PirateBox_DIY http://wiki.daviddarts.com/Debian_on_the_Seagate_Dockstar http://wiki.daviddarts.com/Debian_on_the_Seagate_Dockstar_Post-Installation PirateBox is a self-contained mobile communication and file sharing device. Simply turn it on to transform any space into a free and open communications and file sharing network. it utilizes Free, Libre and Open Source software (FLOSS) to create mobile wireless communications and file sharing networks where users can anonymously chat and share images, video, audio, documents, and other digital content. So you can share and even chat easily by your device.

Private and Secure PirateBox is designed to be private and secure. No logins are required and no user data is logged. Users remain completely anonymous - the system is purposely not connected to the Internet in order to subvert tracking and preserve user privacy. Simply turn it on and transform any space into a free communication and file sharing network. Users within range of the device (mobile, laptop, computers and routers) can join the PirateBox open wireless network from any wifi-enabled device and begin chatting and sharing files immediately. When users join the PirateBox wireless network and open a web browser, they are automatically redirected to the PirateBox welcome page. Users can then immediately begin chatting and/or uploading or downloading files. Note: to lean How to run piratebox on your router, Plug Computer and laptops see the document titled piratebox-supplement

Install PirateBox on a Mobile Phone


Following instruction work fine with any phone with Android, root and WiFi devices such as HTC Hero (Sprint)
http://forum.xda-developers.com/showthread.php?s=470a5b0f17210a1bedafce66ea090796&t=935157 http://fun2code-blog.blogspot.com/

Requirements

Android Device root Wireless Tether App (market or find the attachment) PAW Server ( Attached to the document) SDCard Pirate Lunchbox (Not necessary) BatteryPack (Not Necessary) First, get on the internet and download the "Wireless Tether for Root Users" app. This will establish our PirateBox Network. Set up the name to "PirateBox" or anything you like. Make the network "open" Download and install the APK below. This version of PAW Server includes PirateBox, and the forwarding stuffz. Credits to joschi70 Make a folder called "piratebox" on the root of the SDCard Next, Start the Tether app. Start PAW Server Finally, test the system out by uploading a file from another device. If all works well, the file will be at the folder called "piratebox" under the "html" folder where the pages are. EXTRA: For an almost-exact replica of the original PirateBox, place your device in a Pirate lunchbox with a battery pack. This works by the users joining the "PirateBox" network. PAW Server then serves the site. The page uses BeanShell Code because PAW Server does not like PHP and because BeanShell is

1. 2. 3. 4. 5. 6. 7. 8.

supported by PAW. In the recent versions, joschi70 has changed PirateBox from a half-working project to a fully-working install-on-the-fly system. He has redesigned PirateBox to an almostprecise replica of the original PirateBox. He is also the one to get forwarding woking, You have to use "Wireless Tether for Root Users" and NOT the native tethering in ROMS like CyanogenMOD and MIUI. In fact, DO NOT use a rom with Native Tethering functionality. It screws up the ENTIRE connection to PirateBox. Sense is proven to work, since this was all tested on a Sprint Hero. MotoBlur and TouchWiz are not yet proven. EDIT: Attached is a "server.txt" without the 2MB limit added by PAW. Rename the "server.txt" to "server.xml". Then, place "server.xml" in "sdcard/paw/conf/server.xml". Also, installation process is alot simpler thanks to Joschi70. He is the developer of PAW and has made an APK with PirateBox built in. His version looks more like the original and works more efficiently.

wifi_tether_v3_1-beta6 for android http://code.google.com/p/android-wifi-tether This program enables tethering (via wifi) for "rooted" handsets running android (such as the Android DevPhone 1). Clients (your laptop for example) can connect via wifi (ad-hoc mode)and get access to the internet using the 3G, 2G mobile connection which is established by the handset. This application requires a "rooted"-device and (probably) a custom-kernel which supports netfilter (iptables)!

OpenBTS
OpenBTS (Open Base Transceiver Station) is a UNIX software-based GSM access point, allowing standard GSM-compatible mobile phones to make telephone calls without using existing telecommunication providers' networks. It can be installed and operated at about 1/10 the cost of current technologies, but that will still be compatible with most of the handsets that are already in the market. That uses a software radio to present a GSM air interface to standard 2G GSM handset and uses a SIP softswitch or PBX to connect calls. (You might even say that OpenBTS is a simplified form of IMS that works with 2G feature-phone handsets.) The combination of the globalstandard GSM air interface with low-cost VoIP backhaul forms the basis of a new type of cellular network that can be deployed and operated at substantially lower cost than existing technologies in many applications, including rural cellular deployments and private cellular networks in remote areas. that offers a completely regular GSM air interface (Um) to standard GSM handsets and connects calls using the Asterisk VoIP PBX. This 'flat' system architecture completely differs from the conventional GSM hierarchical architecture. OpenBTS replaces the traditional GSM operator network switching subsystem (http://en.wikipedia.org/wiki/Network_switching_subsystem ) infrastructure, from the Base Transceiver Station (BTS) upwards. Instead of forwarding call traffic through to an operator's mobile switching centre (MSC) the calls are terminated on the same box by forwarding the data onto the Asterisk PBX via SIP and Voice-over-IP (VoIP).

An actual BTS device (Siemens BS11BTS)

A BTS mounted on a building

To improve the quality of the received signal, often two receiving antennas are used, placed at an equal distance to an uneven multiple of a quarter of wavelength (for 900 MHz the wavelength it is 30 cm). This technique, known as antenna diversity or space diversity, avoids interruption caused by path fading. The antennas can be spaced horizontally or vertically. Horizontal spacing requires more complex installation, but brings better performance. See: http://en.wikipedia.org/wiki/Diversity_scheme The reference air interface (Um) uses a software-defined radio (SDR) on top of the Universal Software Radio Peripheral (USRP) USB board. http://en.wikipedia.org/wiki/Air_interface , http://en.wikipedia.org/wiki/Software-defined_radio

Some important definitions: GSM is a cellular network, which means that cell phones connect to it by searching for cells in the immediate vicinity. There are five different cell sizes in a GSM networkmacro, micro, pico, femto and umbrella cells. The longest distance the GSM specification supports in practical use is 35 kilometres (22 mi).it is a standard set developed by the European Telecommunications Standards Institute (ETSI) to describe technologies for second generation (or "2G") digital cellular networks.

GSM cell site antennas in the Deutsches Museum, Munich, Germany

(SIP):The Session Initiation Protocol (SIP) is an IETF-defined signaling protocol widely used for controlling communication sessions such as voice and video calls over Internet Protocol (IP). Other SIP applications include video conferencing, streaming multimedia distribution, instant messaging, presence information, file transfer and online games. IMS: The IP Multimedia Subsystem or IP Multimedia Core Network Subsystem (IMS) is an architectural framework for delivering Internet Protocol (IP) multimedia services. It was originally designed by the wireless standards body 3rd Generation Partnership Project (3GPP), as a part of the vision for evolving mobile networks beyond GSM. Air interface: In mobile or wireless communication, the air interface is the radio-based communication link between the mobile station and the active base station. In GSM/UMTS, the various UTRA standards are air interfaces, and are also (but not exclusively) referred to as "access modes. USRP: The Universal Software Radio Peripheral (USRP) products are a family of computerhosted hardware offered by Ettus Research LLC and its parent company, National Instruments, for making software radios. The USRP product is intended to be a comparatively inexpensive hardware device for software radio. The USRP hardware connects to a host computer through a high-speed USB or Gigabit Ethernet link. The connection enables host-based software to control the USRP hardware and prepare signals for transmission or reception. The USRP family was designed for flexibility, allowing developers to make their own daughterboards for specific needs with regard to connectors, different frequency bands, etc. For more information refer to: http://en.wikipedia.org/wiki/Universal_Software_Radio_Peripheral

USRP platform

Basic RX and Basic TX daughterboards

Asterisk is a software implementation of a telephone private branch exchange (PBX); http://en.wikipedia.org/wiki/Private_branch_exchange it allows attached telephones to make calls to one another, and to connect to other telephone services including the public switched telephone network (PSTN) and Voice over Internet Protocol (VoIP) services. Its name comes from the asterisk symbol, *. Originally designed for Linux, Asterisk also runs on a variety of different operating systems including NetBSD, OpenBSD, FreeBSD, Mac OS X, and Solaris. A port to Microsoft Windows is known as AsteriskWin32. Asterisk is especially small enough to run in an embedded environment like Customer-premises equipment-hardware running OpenWrt (it's already explained ). With Asterisk you turn an ordinary computer into a communications server. to get more information about how to install and use asterisk refer to the the document title with name: VoIP Cookbook: Building your own Telecommunication Infrastructure By Onno W. Purbo Anton Raharja To configure Asterisk into an operational system, the administrator must: Create channels/devices that allow Asterisk to communicate through a voice path that uses that channel and/or devices. These can be VoIP, or TDM, or analogue telephony devices. compose a dial plan, written in the Asterisk control language, to express the algorithm or control flow Asterisk uses to respond when calls are presented to it over these channels. Asterisk can be used for many specific applications and a customized dial plan has to be created specifically for each purpose, such as the functionality of a PBX. Asterisk is thus a 'construction kit' for building PBXs, rather than a PBX in itself, as is commonly thought. Asterisk is configured by a set of configuration text files. One of these, extensions.conf, contains the operational flow logic of Asterisk. A native scripting language is used to define the elements of process control, namely variables, procedural macros, contexts, extensions, and actions. A context groups all the valid destination numbering codes which apply to a set of channels on which incoming (to Asterisk) calls can be presented. These numbering codes, called extensions (even though they often are not) are the starting points for the scripts which instruct Asterisk how to process calls made to those numbers within that context.

To clarify: contexts define the source of a call, and extensions define its destination. Because each channel declares a context, the dial plan restricts and permits which extensions and facilities its device may access. Extensions consist of possibly multiple steps of execution, each performing either logical operations, directing program flow, or executing one of the many included applications available in Asterisk. Applications are loadable modules that perform specialized operations, such as dial a telephone number or another internal extension (app_dial), perform conferencing services

(app_meetme), or handle the operations of voice mail (app_voicemail). The plethora of applications available provide a unique capability and tool set to formulate algorithms that can perform a large array of different, customized telephony scenarios. Applications control the Asterisk core functions through a set of internal operation primitives, that are organized in an extensible fashion through a modular architecture and application programming interfaces (APIs): http://en.wikipedia.org/wiki/Application_programming_interface Programming an Asterisk system can also be accomplished via separate, external applications using the Asterisk Gateway Interface: See: http://en.wikipedia.org/wiki/Asterisk_Gateway_Interface The Asterisk Gateway Interface (AGI) is a software interface and communications protocol for inter-process communication with Asterisk. In this, external, user-written programs, are launched from the Asterisk dial plan via pipes to control telephony operations on its associated control and voice channels. It is similar to the CGI feature of web servers in that any language can be used to write the external program which communicates with Asterisk via the standard streams, stdin and stdout. There are several graphical user interfaces (GUIs) for Asterisk. These interfaces allow administrators to view, edit, and change various aspects of Asterisk via a web interface. As of version 1.8, a GUI labeled Asterisk-GUI is being developed alongside Asterisk by Digium. There are other GUIs, such as FreePBX. Other attempts to simplify Asterisk installation have been made, trixbox (formerly Asterisk at home (A@H)) is a popular distribution of Asterisk that includes Asterisk and FreePBX. PBX in a Flash (PIAF) is another such distribution.

Digium has also packaged a variant entitled AsteriskNow, which is a customized Linux installation and includes FreePBX and all ancillary software to provide an "off-the-shelf" PBX, requiring only that the user prepare the requisite dial plans (see above) and connect the necessary hardware. The target market for AsteriskNow is the administrator who wishes to set up a PBX using Asterisk, but who may not have the experience in server configuration to perform the initial setup of a base Asterisk installation. Asterisk is a core component in many "PABX in a box" commercial products and Open Source projects. Some of the commercial products are hardware and software bundles, for which the manufacturer supports and releases the software as Open Source. Examples are TrixBox and Elastix. Asterisk is also included in the LinuxMCE home entertainment/automation system

See more information here: http://en.wikipedia.org/wiki/LinuxMCE And grab linuxMCE here: http://wiki.linuxmce.org/index.php/Main_Page http://www.linuxmce.org

Below are links to download the currently supported versions of Asterisk and various Asteriskrelated open source projects. AsteriskNOW is the premier ready-to-run distribution of open source Asterisk. AsteriskNOW is an ISO CD image that allows you to install Linux, Asterisk and the FreePBX GUI in a single simple install. Download it from here: http://www.asterisk.org/downloads

Asterisk creates a PBX that rivals the features and functionality of traditional telephony switches. Asterisk is cost-effective, low-maintenance, and flexible enough to handle all voice and data networking. With Asterisk software, Telephony hardware, and a common PC, anyone can replace an existing switch or complement a PBX by adding VoiceOverIP, voicemail, conferencing, and many other capabilities. Asterisk integrates with analog phones and most standards-based IP telephone handsets and software. Get Asterisk for windows from http://www.asteriskwin32.com

Starting OpenBTS
1. Get a Range Networks full-scale basestation. Range Networks produces several GSM basestation models based on the Range's own radio hardware and the commercial ("C") release of OpenBTS. These units are available in single- and multi-ARFCN configurations, at power levels ranging from 100 mW to 50 W. Any of these units can also be used to run the public release. This is probably the best choice for users who want to use OpenBTS for normal communications, who want to experiment with OpenBTS in full-range configurations or who require commercial support or other professional services. For more information on these products, see their website : http://www.rangenetworks.com and contact: sales@rangenetworks.com . 2. Get a Range development kit. You can buy one online here: http://kestrelsignalprocessing.mybigcommerce.com/products/OpenBTS-DevelopmentKit.html Price: $3,500.00 SKU:270833 Weight: 4.00 LBS

Product Description The basic hardware you need to run an short-range, experimental, non-commericial OpenBTS system -- modified USRP w/ USB cable, power supply, an antenna -- 1 RFX1800 daughterboard -- an installed 52MHz clock board -- a mini-ITX board configured with

1) the latest stable public release (P2.6) OpenBTS software 2) the libraries and software that support OpenBTS 3) Asterisk and Ubuntu 9.10 Board includes 8GB IDE flash drive, 2GB RAM, and a power supply. The GSM band of operation is configurable via software. This is probably the best choice for users who want to experiment with the public ("P") release of OpenBTS in a desktop setting, without a lot of additional up-front effort. The current development kit consists of :
o o o o

a modified Ettus USRP-1, a 52 MHz TCXO clock generator, an Ettus RFX-900/1800 card and a mini-ITX PC with GNU Radio and the latest public release of OpenBTS pre-installed. 3. Roll your own. The public release of OpenBTS is compatible with several digital radio products from Ettus Research (http://www.ettus.com/products), requiring varying degrees of hardware modification and yielding varying degrees of performance. For more information on the "roll your own" approach, take a look at the old public wiki. http://gnuradio.org/redmine/projects/gnuradio/wiki/OpenBTS#I-Want-to-Run-OpenBTS Note: The "C" release of OpenBTS will not work with Ettus hardware.

How is OpenBTS P2.8 "Opelousas" different from the previous P2.6 "Mamou" release? The biggest differences are database-driven configuration and the use of "realtime" Asterisk, but there are some other new features as well. Where can I get the P2.8 code? Live SVN Repository The best way to get OpenBTS is by pulling the code directly from our source code repository as an anonymous read-only user. svn co http://wush.net/svn/range/software/public If you're planning on developing for OpenBTS, we recommend using git instead of svn. This allows you to commit and test your code locally, before uploading it to the main repository.

git svn init http://wush.net/svn/range/software/public openbts git svn fetch

********************************************** Differences from the P2.6 Release If you are accustomed to working with the P2.6 release, the transition to P2.8 will mean some big changes. Why? The short answer is that this is the why that the commercial release is evolving and the architecture of the official public release tracks of the commercial release. Database-Driven Configuration In P2.8, configuration is no longer from a text file but from an sqlite3 database at /etc/OpenBTS/OpenBTS.db. Any change of a non-static parameter in this database will result in a change in OpenBTS operation within about 2 seconds. In the OpenBTS "tools" directory there is a Python script called translateConfig.py the will convert an old-style configuration file into an SQL file sthat can be fed into sqlite3 to generate a configuration database. Why? Database-driven configuration allows external applications to control critical operating parameters of the OpenBTS system. This opens the way for web-based and automated configuration management tools and allows many operating parameters to be changed without disrupting the service. Real-Time Asterisk In P2.8, OpenBTS no longer uses Asterisk's internal SIP registry as an HLR replacement. Instead, it uses a new component called the subscriber registry, based on an sqlite3 database at /var/lob/asterisk/sqlite3dir/sqlite3.db. This database includes tables for both SIP user registration and call routing in a configuration called realtime asterisk (http://www.voipinfo.org/wiki/view/Asterisk+RealTime+Sip ). There are three important implications: 1. OpenBTS no longer performs SIP REGISTER exchanges with Asterisk directly. Instead, SIP REGISTER methods are sent to a new server called sipauthserver, the SIP interface of the subscriber registry. 2. OpenBTS handsets can no longer be provisioned into Asterisk through /etc/asterisk/sip.conf. Instead, they must be provisioned into the subscriber registry. Otherwise, Asterisk has no way to know the registered IP address of the handset. 3. The dialplan configuration now uses explicit database lookups through the ODBC interface to route calls. For example:

[phones] ; This is the context for handsets provisioned through the realtime database. ; This assumes that OpenBTS units all are running their SIP interfaces on port 5062. exten => _N.,1,Set(Name=${ODBC_SQL(select dial from dialdata_table where exten = \"${EXTEN}\")}) exten => _N.,n,GotoIf($["${Name}" = ""] ?outbound-trunk,${EXTEN},1) exten => _N.,n,Set(IPAddr=${ODBC_SQL(select ipaddr from sip_buddies where name = \"${Name}\")}) exten => _N.,n,GotoIf($["${IPAddr}" = ""] ?outbound-trunk,${EXTEN},1) exten => _N.,n,Dial(SIP/${Name}@${IPAddr}:5062)

Why? The real-time Asterisk approach allows multiple programs to access the provisioning databases directly, which opens the way for a wide range of provisioning and account-management tools. It also allows smqueue to run independently of Asterisk and simplifies integration of OpenBTS with other (non-Asterisk) switches and PBXs.

Syslog OpenBTS P2.8 uses syslog (or rsyslog) for event and message logging. This is a big improvement over the old system of logging to a regular file. Why? The advantages should be obvious. "Why not SNMP?" Because it needs more attempts to get around it. Bug Fixes There are lots of bug fixes in P2.8, especially in the SIP side. P2.8 has been tested successfully with Asterisk 1.8 and FreeSWITCH and should work with any softswitch. If it does not, that is a bug that should be reported.

Other Features There are some other minor features included in P2.8:

Rest octet support in system information messages. Better RRLP support, including an RRLP aiding server. Realtime reporting of radio channel activity to an externally visible database. The TMSI table has also been moved to an externally visible database, although it will probably be moving into the subscriber registry in future releases.

***************************************************

Using git-svn is described in numerous places, here is an example: Howto use Git and svn together Git(http://git.or.cz ) it can be really useful, especially if you spend lot of time coding off-line .This is a really small howto that describes how to work on a project versioned with svn (maybe taken from KDE repository) using git. Whatre the advantages? Since Git is a distributed revision control system (while svn is a centralized one) you can perform commits, brances, merges, on your local working dir without being connected to internet. Next time youll be online, you will be able to push your changes back to the central svn server. Steps to follow: Youve to: 1. install git and git-svn 2. create the working dir: mkdir strigi 3. init your git working dir: cd strigi && git-svn init https://svn.kde.org/home/kde/trunk/kdesupport/strigi git-svn init command is followed by the address of the svn repository (in this case we point to strigis repository) 4. Find a commit regarding the project (you can get it from cia version control: http://cia.vc ) Warning: the command git-log will show projects history starting from this revision.

5. Perform the command git-svn fetch rREVISION Where REVISION is the number obtained before. 6. Update your working dir: git-svn rebase Now youll be able to work on your project using git as revision control system. To keep update your working copy just perform: git-svn rebase You can commit your changes to the svn server using the command: git-svn dcommit In this way each commit made with git will be transformed into a svn one. Solve git-svn rebase problems While adding new cool features to your program, you may experiment some problem when synchronizing with the main development tree. In fact you have to commit all local modifications (using the git-commit command) before invoking git-svn rebase. Sometimes it isnt reasonable since your changes are not yet ready to be committed (you havent finished/tested/improved your work). But dont worry, git has a native solution also for this problem, just follow these steps: 1. 2. 3. 4. put aside your changes using the command: git-stash update your working copy using: git-svn rebase as usual take back your changes typing: git-stash apply clear the stash typing: git-stash clear

After the first step all your uncommitted changes will disappear from the working copy, so youll be able to perform the rebase command without problems. For further informations read git-stash man page. Standalone "Tarball" If you have a nostalgic interest in OpenBTS, you can also download old gzip-compressed tarfiles of OpenBTS P2.8 components from this page at SourceForge: http://sourceforge.net/projects/openbts/files . These will be periodically updated, but almost always be behind the repository above.

Building , install and run the code Here is an instructions on how to build and install a simple, one-PC, one-BTS system. This is the appropriate starting point for new users. advanced users, should follow multiBTS for instructions on operating a more complicated setup.

Building, Installing and Running OpenBTS Here is the installation of a single instance of OpenBTS on a single PC with a single radio. This default configurations support this setup, and it's the right place to start. A complete installation of OpenBTS P2.8 comprises these components:

OpenBTS itself. This is the GSM implementation from the TDMA part of L1 up through L3 and the L3/L4 boundary. Its SIP interface is normally on port 5062. This is located in openbts/trunk. Transceiver. This is the software radiomodem, implementing the lower part of L1. OpenBTS starts the transceiver automatically. These are located in openbts/trunk/Transceiver*. A SIP PBX or softswitch (Asterisk, FeeeSWITCH, etc.) This component connects speech calls. Its SIP interface is normally on port 5060. This is not packaged with OpenBTS. Sipauthserver. This is the SIP registration and authorization server, used to process location updating requests from OpenBTS and perform corresponding updates in the subscriber registry database. Its SIP interface normally runs on port 5064. This is located in subscriberRegistry/trunk. Smqueue. This is the store-and-forward text messaging server. It needs to be started independently of OpenBTS. Its SIP interface is normally run on port 5063. Smqueue is not required in installations that do not support text messaging. This is located in smqueue/trunk. Rrlpserver. This is the RRLP aiding server and it is run as a CGI script in a web server. Rrlpserver is not required if RRLP is not being used. This is located in RRLP/trunk.

Hardware OpenBTS can be run a variety of hardware. You must first note the specific hardware being used. There are three distinct types:

Range Equipment (e.g., RAD1) Ettus Research USRP1? Ettus UHD Devices (e.g., USRP2, N200 Series) *************************************

N200 and N210 Device Notes


Clock References Internal Reference The N210 has a variety of clock configurations that may work or not work with OpenBTS to varying degrees. All N210's include an on-board 2.5ppm TCXO that serves as a stable reference, though not GSM specification compliant. The internal TXCO is used if the '--with-extref' option is not specified and no GPSDO kit is present. External Reference The front panel input can be used with any external reference and is enabled with the '--withextref' configure option. From the UHD manual: http://files.ettus.com/uhd_docs/manual/html/usrp2.html , the reference specifications are: Using an external 10 MHz reference clock, square wave will offer the best phase noise performance, but sinusoid is acceptable. The reference clock requires the following power level: USRP2: 5 - 15 dBm N2XX: 0 - 15 dBm Of various clock options, the worst performing case arises when the external reference is enabled with no reference present causing the internal oscillator to run free. The resulting center frequency can be off by a large amount - visible as many kHz on a spectrum analyzer. Handset compatibility in this specific configuration varies, but performance is very likely to be poor do to the frequency error.

Ettus Research GPSDO Kit For use of the optional, but recommended, GPSDO Kit, see the Ettus Research installation instructions. : http://www.ettus.com/downloads/gpsdo-kit.pdf Please note the J510 setting which switches the reference connection from front panel connector to the GPSDO clock; pin 1 of the jumper pins is noted by the large white triangle. Improper setting of the jumper will disable use of the GPSDO and cause poor clocking performance. Also note that the GPSDO Kit configures automatically through the UHD driver. The '--withextref' configure setting is not necessary and has no effect. *************************************

Required Libraries/Utilities

To compile the various parts of OpenBTS (minus the PBX) you'll need the following packages: autoconf libtool libosip2 libortp libusb-1.0 g++ sqlite3 libsqlite3-dev (sipauthserve only) erlang (RRLP Server only) These can be installed (on a Debian-flavored unix distro) with the following command:

sudo apt-get install autoconf libtool, libosip2-dev, libortp-dev, libusb-1.0-0-dev, g++, sqlite3, libsqlite3-dev, erlang

System Diagram
In this diagram, Black links are network connections (SIP). Red links are file system connections (sqlite3 lookups). Blue links are ODBC (network/local DB lookups).

Build and Install OpenBTS and the Transceiver


Building OpenBTS OpenBTS should, in principle, build and run on any Unix-like operating system. However, in practice, most of our development is done on Ubuntu 10 systems, so these are best-supported. Building for Range equipment is easiest, as it has no external dependencies. Just run the following commands: autoreconf -i ./configure make If you are "rolling your own" with Ettus USRP hardware, you will also need to install GNU Radio. The configure script does not check this, since the default build is for Range Networks'

RAD1 hardware. For more information on installing GNU Radio follow installation section. (If you ordered a Range Developers' Kit, GNU Radio is already installed and if you are using a Range basestation unit, you do not need GNU Radio at all.) Make sure to install something after 3.3.0, but before 3.5.0 (where they removed USRP1 support). With that installed, run the following 'auto-foo' process. Standard two daughterboard configuration (Tx side A, Rx side B): autoreconf -i ./configure --with-usrp1 make Single daughterboard configuration (Tx and Rx on side A). Side B is unused. autoreconf -i ./configure --with-usrp1 --with-singledb make For all other Ettus Hardware(USRP2, B100, N200 and E100 series), you use the UHD (universal hardware device) libraries. The download of these libraries is demonstrated here :http://code.ettus.com/redmine/ettus/projects/uhd/wiki and the installation explained in next sections in this document. Configuration options depend on the type of device. USRP2 and N200 series require host-based resampling support: autoreconf -i ./configure --with-uhd --with-resamp Make B100 and E100 series: autoreconf -i ./configure --with-uhd make Additional built time options for UHD devices include 10 MHz external reference support. For example, to use the front panel reference input on a N210, configure with the following options: autoreconf -i ./configure --with-uhd --with-resamp --with-extref make

With the build resolved, you'll need to build and link the transceiver appropriate for your hardware. For the USRP/UHD installs: #(from OpenBTS root) cd Transceiver52M make cd ../apps ln -s ../Transceiver52M/transceiver .

#and for the USRP1, install std_inband.rbf sudo mkdir -p /usr/local/share/usrp/rev4/ sudo cp ../Transceiver52M/std_inband.rbf /usr/local/share/usrp/rev4/ If you are using a Range Networks basestation unit these links are (from OpenBTS root) cd TransceiverRAD1 make ln -s transceiver ../apps/transceiver ln -s ezusb.ihx ../apps/ezusb.ihx ln -s fpga.rbf ../apps/fpga.rbf And GNU Radio is not required. Configuring OpenBTS With OpenBTS built, you now need to configure it to run correctly. There are a two key files that must be created for this to happen.

1) /etc/OpenBTS/OpenBTS.db OpenBTS.db is the database store for all OpenBTS configuration. It must be installed at /etc/OpenBTS, which likely does not exist. So, to create this file: (from the OpenBTS directory) sudo mkdir /etc/OpenBTS sudo sqlite3 -init ./apps/OpenBTS.example.sql /etc/OpenBTS/OpenBTS.db This generates a lot of stock configuration options. You can see these listed here: ***********************************
CLI.Prompt Prompt for the OpenBTS command line interface. Control.GSMTAP.TargetIP Target IP address for GSMTAP packets; the IP address of

Wireshark, if you use it for GSM.


Control.LUR.AttachDetach Attach/detach flag. Set to 1 to use attach/detach procedure,

0 otherwise. This will make initial LUR more prompt. It will also cause an unregstration if the handset powers off and really heavy LUR loads in areas with spotty coverage.
Control.LUR.CachedAuthentication If not NULL, use RAND-SRES pairs cached in the

TMSI table for authentication. If this method is used, it is important that the TMSI Table be in persistent storage.
Control.LUR.DefaultAuthenticationAccept If not NULL, provisioned handsets will be

accepted for authentication in the absence of any defined authentication method. For commercial networks this value should probably be NULL.
Control.LUR.FailedRegistration.Message If defined, send this text message, followed

by the IMSI, to unprovisioned handsets that are denied registration.


Control.LUR.FailedRegistration.ShortCode

The return address for the failed registration message. If the message is defined, this must also be defined. by the IMSI, to provisioned handsets when they attach on Um.

Control.LUR.NormalRegistration.Message If defined, send this text message, followed

Control.LUR.NormalRegistration.ShortCode The return address for the normal

registration message. If the message is defined, this must also be defined.

Control.LUR.OpenRegistration

A regular expression. If not NULL, allow unprovisioned handsets with matching IMSIs to attach in Um. the IMSI, to unprovisioned handsets when they attach on Um due to open registration.

Control.LUR.OpenRegistration.Message If defined, send this text message, followed by

Control.LUR.OpenRegistration.ShortCode The return address for the open registration

message. If the message is defined, this must also be defined.


Control.LUR.QueryClassmark If not NULL, query every MS for classmark during

LUR.
Control.LUR.QueryIMEI If not NULL, query every MS for IMSI during LUR. Control.LUR.SR-HTTPAuthentication If not NULL, use the HTTP interface of the

subscriber registry server for authentication.


Control.LUR.SendTMSIs If not NULL, send new TMSI assignments to handsets that

are allowed to attach.


Control.LUR.UnprovisionedRejectCause Reject cause for location updating failures for

unprovisioned phones. Reject causes come from GSM 04.08 10.5.3.6. Reject cause 0x04, IMSI not in VLR, is usually the right one.
Control.NumSQLTries Number of times to retry SQL queries before declaring a

database access failure.


Control.Reporting.PhysStatusTable File path for channel status reporting database.

Static.
Control.Reporting.TMSITable File path for TMSITable database. Static. Control.TMSITable.MaxAge Maximum allowed age for a TMSI in hours. Control.TMSITable.MaxSize Maximum size of TMSI table before oldest TMSIs are

discarded.
Control.TestCall.Port Port for exchanging L3 packets with the testcall feature. Control.VEA If not NULL, user very early assignment for speech call establishment.

See GSM 04.08 Section 7.3.2 for a detailed explanation of assignment types. If VEA is selection, GSM.CellSelection.NECI should be set to 1. See GSM 04.08 Sections 9.1.8 and 10.5.2.4 for an explanation of the NECI bit.
GSM.CCCH.AGCH.QMax Maximum number of access grants to be queued for

transmission on AGCH before declaring congrestion.

GSM.CCCH.CCCH-CONF CCCH configuration type. See GSM 10.5.2.11 for

encoding. Value of 1 means we are using a C-V beacon. Any other value selects a C-IV beacon.
GSM.CCCH.PCH.Reserve Number of CCCH subchannels to reserve for paging. GSM.CellSelection.CELL-RESELECT-HYSTERESIS Cell Reselection Hysteresis.

See GSM 04.08 10.5.2.4, Table 10.5.23 for encoding. Encoding is 2N dB, values of N are 0...7 for 0...14 dB.
GSM.CellSelection.MS-TXPWR-MAX-CCH Cell selection parameters. See GSM

04.08 10.5.2.4.
GSM.CellSelection.NCCsPermitted NCCs Permitted. An 8-bit mask of allowed NCCs.

Unless you are coordinating with another carrier, this should probably just select your own NCC.
GSM.CellSelection.NECI NECI, New Establishment Causes. This must be set to 1 if

you want to support very early assignment. See GSM 04.08 10.5.2.4, Table 10.5.23 and 04.08 9.1.8, Table 9.9.
GSM.CellSelection.Neighbors ARFCNs of neighboring cells. GSM.CellSelection.RXLEV-ACCESS-MIN Cell selection parameters. See GSM 04.08

10.5.2.4.
GSM.Channels.C1sFirst If not NULL, allocate C-I slots first, starting at C0T1.

Otherwise, allocate C-VII slots first. Static.


GSM.Channels.NumC1s Number of Combination-I timeslots to configure. The C-I slot

carries a single full-rate TCH, used for speech calling. Static.


GSM.Channels.NumC7s Number of Combination-VII timeslots to configure. The C-

VII slot carries 8 SDCCHs, useful to handle high registration loads or SMS. If C0T0 is C-IV, you must have at least one C-VII also. Static.
GSM.Identity.BSIC.BCC GSM basestation color code; lower 3 bits of the BSIC. BCC

values in a multi-BTS network should be assigned so that BTS units with overlapping coverage do not share a BCC. This value will also select the training sequence used for all slots on this unit.
GSM.Identity.BSIC.NCC GSM network color code; upper 3 bits of the BSIC. Assigned

by your national regulator. Must be distinct from NCCs of other GSM operators in your area.
GSM.Identity.CI Cell ID, 16 bits. Should be unique.

GSM.Identity.LAC Location area code, 16 bits, values 0xFFxx are reserved. For multi-

BTS networks, assign a unique LAC to each BTS unit. (That is not the normal procedure in conventional GSM networks, but is the correct procedure in OpenBTS networks.)
GSM.Identity.MCC Mobile country code, 2 or 3 digits. Defined in ITU-T E.212. GSM.Identity.MNC Mobile network code; Must be 3 dgits. Assigned by your national

regulator.
GSM.Identity.ShortName Network short name, displayed on some phones. Optional

but must be defined if you also want the network to send time-of-day.
GSM.Identity.ShowCountry If not NULL, tell the phone to show the country name

based on the MCC.


GSM.MS.Power.Damping Damping value for MS power control loop. GSM.MS.Power.Max Maximum commanded MS power level in dBm. GSM.MS.Power.Min Minimum commanded MS power level in dBm. GSM.MS.TA.Damping Damping value for timing advance control loop. GSM.MS.TA.Max Maximum allowed timing advance in symbol periods. Ignore

RACH bursts with delays greater than this. Can be used to limit service range.
GSM.MaxSpeechLatency Maximum allowed speech buffering latency, in 20 ms

frames. If the jitter is larger than this delay, frames will be lost.
GSM.RACH.AC Access class flags. This is the raw parameter sent on the BCCH. See

GSM 04.08 10.5.2.29 for encoding. Set to 0 to allow full access. If you do not have proper PSAP integration, set to 0x0400 to indicate no support for emergency calls.
GSM.RACH.MaxRetrans Maximum RACH retransmission attempts. This is the raw

parameter sent on the BCCH. See GSM 04.08 10.5.2.29 for encoding.
GSM.RACH.TxInteger Parameter to spread RACH busts over time. This is the raw

parameter sent on the BCCH. See GSM 04.08 10.5.2.29 for encoding.
GSM.RADIO-LINK-TIMEOUT L1 radio link timeout. This is the raw parameter sent

on the BCCH; see GSM 10.5.2.3 for encoding. Should be coordinated with T3109.
GSM.RRLP.ACCURACY Requested accuracy of location request. K in 10(1.1**K-1).

See 3GPP 03.32, sect 6.2

GSM.RRLP.ALMANAC.REFRESH.TIME How often the almanac is refreshed, in

hours
GSM.RRLP.ALMANAC.URL URL of almanac source. GSM.RRLP.EPHEMERIS.REFRESH.TIME How often the ephemeris is refreshed, in

hours.
GSM.RRLP.EPHEMERIS.URL URL of ephemeris source. GSM.RRLP.RESPONSETIME Mobile timeout. (OpenBTS timeout is 130 sec = max

response time + 2.) N in 2**N. See 3GPP 04.31 sect A.2.2.1


GSM.RRLP.SEED.ALTITUDE Seed altitude in meters wrt geoidal surface. GSM.RRLP.SEED.LATITUDE Seed latitude in degrees. -90 (south pole) .. +90 (north

pole)
GSM.RRLP.SEED.LONGITUDE Seed longitude in degrees. -180 (west of greenwich)

.. 180 (east)
GSM.RRLP.SERVER.URL URL of RRLP server. GSM.Radio.Band The GSM operating band. Valid values are 850 (GSM850), 900

(PGSM900), 1800 (DCS1800) and 1900 (PCS1900). For most Range models, this value is dictated by the hardware and should not be changed. Static.
GSM.Radio.C0 The C0 ARFCN. Static. GSM.Radio.MaxExpectedDelaySpread Expected worst-case delay spread in symbol

periods, roughly 3.7 us or 1.1 km per unit.


GSM.Radio.PowerManager.MaxAttenDB Maximum transmitter attenuation level, in

dB wrt full scale on the D/A output. This sets the minimum power output level in the output power control loop.
GSM.Radio.PowerManager.MinAttenDB Minimum transmitter attenuation level, in dB

wrt full scale on the D/A output. This sets the maximum power output level in the output power control loop.
GSM.Radio.PowerManager.NumSamples Number of samples averaged by the output

power control loop.


GSM.Radio.PowerManager.SamplePeriod Sample period for the output power control

loop.

GSM.Radio.PowerManager.TargetT3122 Target value for T3122, the random access

hold-off timer, for the power control loop.


GSM.Radio.RSSITarget Target uplink RSSI for MS power control loop, in dB wrt to

A/D full scale. Should be 6-10 dB above the noise floor.


GSM.Radio.RxGain Receiver gain setting in dB. Ideal value is dictacted by the

hardware. This database parameter is static but the receiver gain can be modified in real time with the CLI rxgain command. Static.
GSM.Timer.T3113 Paging timer T3113 in ms. This is the timeout for a handset to

respond to a paging request. This should usually be the same as SIP.Timer.B in your VoIP network.
GSM.Timer.T3122Max Maximum allowed value for T3122, the RACH holdoff timer,

in milliseconds.
GSM.Timer.T3122Min Minimum allowed value for T3122, the RACH holdoff timer,

in milliseconds.
GSM.Timer.T3212 Registration timer T3212 period in minutes. Should be a factor of 6.

Set to 0 to disable periodic registration. Should be smaller than SIP registration period.
Log.Alarms.Max Maximum number of alarms to remember inside the application. Log.Level Default logging level when no other level is defined for a file. Log.Level.CallControl.cpp Default configuration logs a trace at L3. Log.Level.MobilityManagement.cpp Default configuration logs a trace at L3. Log.Level.RadioResource.cpp Default configuration logs a trace at L3. Log.Level.SMSControl.cpp Default configuration logs a trace at L3. NTP.Server NTP server(s) for time-of-day clock syncing. For multiple servers, use a

space-delimited list. If left undefined, NTP will not be used, but it is strongly recommended.
RTP.Range Range of RTP port pool. Pool is RTP.Start to RTP.Range-1. Static. RTP.Start Base of RTP port pool. Pool is RTP.Start to RTP.Range-1. Static. SIP.DTMF.RFC2833 If not NULL, use RFC-2833 (RTP event signalling) for in-call

DTMF.

SIP.DTMF.RFC2833.PayloadType Payload type to use for RFC-2833 telephone event

packets. If SIP.DTMF.2833 is defined, this must also be defined.


SIP.DTMF.RFC2967 If not NULL, use RFC-2967 (SIP INFO method) for in-call

DTMF.
SIP.Local.IP IP address of the OpenBTS machine as seen by its proxies. If these are all

local, this can be localhost. Static.


SIP.Local.Port IP port that OpenBTS uses for its SIP interface. Static. SIP.MaxForwards Maximum allowed number of referrals. SIP.Proxy.Registration The IP host and port of the proxy to be used for registration and

authentication. This is the subscriber registry, for example.


SIP.Proxy.SMS The IP host and port of the proxy to be used for text messaging. This is

smqueue, for example.


SIP.Proxy.Speech The IP host and port of the proxy to be used for normal speech calls.

This is Asterisk, for example.


SIP.RegistrationPeriod Registration period in minutes for MS SIP users. Should be

longer than GSM T3212.


SIP.SMSC The SMSC handler in smqueue. This is the entity that handles full 3GPP

MIME-encapsulted TPDUs. If not defined, use direct numeric addressing. Normally the value is NULL if SMS.MIMIEType is text/plain or smsc if SMS.MIMEType is application/vnd.3gpp.
SIP.Timer.A INVITE retransmit period in ms. SIP.Timer.B INVITE transaction timeout in ms. This value should usually match

GSM.Timer.T3113.
SIP.Timer.E Non-INVITE initial request retransmit period in ms. SIP.Timer.F Non-INVITE initial request timeout in ms. SIP.Timer.H ACK timeout period in ms. SIP.Timer.I ACK retransmit period in ms. SIP.Timer.J Non-INVITE non-initial request retransmit period in ms. SIP.myPort Port used by the SIP Authentication Server

SMS.DefaultDestSMSC Use this to fill in L4 SMSC address in SMS submission. SMS.FakeSrcSMSC Use this to fill in L4 SMSC address in SMS delivery. SMS.MIMEType This is the MIME Type that OpenBTS will use for RFC-3428 SIP

MESSAGE payloads. Valid values are application/vnd.3gpp.sms and text/plain.


SubscriberRegistry.A3A8 URL of upstream subscriber registry server. Blank (not

NULL) if there is none.


SubscriberRegistry.HTTP.Server URL of the subscriber registry server. SubscriberRegistry.Manager.Title Title of subscriber registry database manager web

page.
SubscriberRegistry.Manager.Url URL of the subscriber registry database manager. SubscriberRegistry.Manager.VisibleColumns Field names in subscriber registry visible

in the database manager.


SubscriberRegistry.db The location of the sqlite3 database holding the subscriber

registry.
SubscriberRegistry.Port - The port for the subscriber registry. Static. TRX.IP IP address of the transceiver application. Static. TRX.Port IP port of the transceiver application. Static. TRX.RadioFrequencyOffset Fine-tuning adjustment for the transceiver. Static.

Most of these only need to be tweaked if you are moving beyond a simple desktop setup. However, a few are required for basic operation. These are:

GSM.Radio.Band - Set this to the GSM band appropriate for your hardware. GSM.Radio.C0 - This is the ARFCN. Set it to something appropriate for your band. Control.LUR.OpenRegistration - Set this to a regular expression:

(http://en.wikipedia.org/wiki/Regular_expression) matching the IMSIs of your test phones. This tells OpenBTS to not reject your handset just because your registration server (below) isn't responding. Useful for debugging and initializing the system. **************************************

ARFCN :Absolute radio-frequency channel number


In GSM cellular networks, an absolute radio-frequency channel number (ARFCN) is a code that specifies a pair of physical radio carriers and channels used for transmission and reception on the Um interface, one for the uplink signal and one for the downlink signal. ARFCNs are defined in GSM Specification 45.005 Section 2. Each ARFCN has a bandwidth of 270.833 kHz. ARFCNs use a channel spacing of 200 kHz in any given GSM band. Uplink-downlink spacing is typically 45 or 50 MHz. Different frequencies (ARFCNs) are used for the frequency-based component of GSMs multiple access scheme (FDMA frequency-division multiple access). Together with the time-based component (TDMA time division multiple access) the physical channel is defined by selecting a certain ARFCN and a certain time slot. Note not to confuse this physical channel with the logical channels (e.g. BCH Broadcast Control Channel) that are time-multiplexed onto it under the rules of GSM Specification 05.03. *************************************

Running OpenBTS Everything should be in place for OpenBTS to run. To do so, run the following command (from the OpenBTS directory) cd apps sudo ./OpenBTS You should see a splash screen describing the project, and then a command-line interface: OpenBTS> ***************************************

Command-line interface listed here


alarms Command List recent alarms. The number of alarms saved in the list is set by the Log.Alarms.Max configuration value.

calls Command List in-progress Q.931 and SMS transactions from the internal transaction table. Displayed information includes:

transaction id The key for the corresponding entry in the transaction table that is currently making use of this channel. SIP call state Q.931/GSM call state time since last state change subscriber IMSI called or calling party number

cellid Command Display or change cell identity parameters. These parameters are:

MCC Mobile Country Code (3 digits) MNC Mobile Network Code (2 or 3 digits) LAC Location Area Code (16 bits, 1-65520 are valid values) CI Cell Identity (16 bits, 0-65535 are valid values)

With no arguments, this command displays the current MCC, MNC, LAC and CI values. With arguments cellid <MCC> <MNC> <LAC> <CI> this command sets the parameters to the given values and updates the corresponding GSM.Indentity.!* configuration table parameters, as described in Section 4.2. Using the command with arguments will also cause the TMSI Table to be cleared.

chans Command This command displays physical channel status from the channel table (Section 4.4) for active dedicated channels. There are no arguments. The reported values are:

TN Timeslot number. chan type The dedicated channel type. transaction id The key for the corresponding entry in the transaction table that is currently making use of this channel. UPFER pct Uplink frame erasure rate, as a percentage. RSSI dB Uplink RSSI at the BTS, in dB with respect to full scale. TXPWR dBm Current uplink transmitter power (from the MS) in dBm. TXTA sym Timing advance in symbol periods. DNLEV dBm Downlink RSSI in dBm as measured by the MS. DNBER pct Downlink bit error rate, as a percentage.

config & unconfig Commands This commands display and modify parameters in the configuration table . The config command can be used to inspect, create or modify a configuration table value. config <pattern> lists all configuration parameters that contain given pattern. config <key> <value> Creates or sets the given key-value pair in the configuration table. unconfig <key> removes the associated key-value pair from the configuration table. For example: OpenBTS> config Example.Value 5 defined new config Example.Value as "5" OpenBTS> config Example.Value Example.Value: 5 OpenBTS> unconfig Example.Value

"Example.Value" removed from the configuration table OpenBTS> config ExampleValue nothing matching "ExampleValue" OpenBTS> The config command is possibly the most useful and powerful command in the interface

endcall Command Force the termination of a call or other transaction. endcall <transactionID>

exit Command The exit command shuts down the OpenBTS and transceiver processes. In embedded applications, OpenBTS is running in a restart loop, so the effect of this command is to restart the OpenBTS GSM stack and its associated transceiver. This process takes about 20 seconds. The exit command with no arguments exits the OpenBTS process immediately. If an argument is given, in seconds, the command will wait up to the given number of seconds for in-progress calls and transactions to clear before exiting. During this wait time, no new calls or transactions will be allowed to start.

load Command Give the current BTS load, in terms of active channels and queue lengths. load The results mean:

SDCCH load The number of active SDCCHs out of the total available. TCH/F load The number of active TCH/Fs out of the total available. AGCH/PCH load The number of queued messages awaiting transmission on the AGCH and PCH. Paging table size The number of MSs currently being paged. Transactions/TMSIs The number of active transactions in the BTS and the size of the TMSI table. T3122 The current value of the T3122 hold-off timer, in seconds. See Section 5.2 for details.

notices Command Print the copyright and legal notices associated with this installation of OpenBTS.

page Command Page a given IMSI. Since there is no real transaction associated with this page, the MS will be rejected when it attempts to establish a dedicated channel to the BTS. This command is provided for testing purposes. page <IMSI>

power Command Inspect or change the downlink power parameters described in Section 5.2. With no arguments, this command displays the current power setting and bounds. With arguments, this command changes the power control bounds. power <minAtten> <maxAtten>

sendsms and sendsimple Commands Either of these commands sends a text message via SMS to a given MS , addressed by IMSI and appearing to originate from a given source address: sendsms <IMSI> <sourceAddress> sendsimple <IMSI> <sourceAddress> You will then be prompted to enter the message text. The difference between these is that sendsms operates directly in the SMS control layers of OpenBTS while sendsimple operates by sending an RFC-3428 SIP MESSAGE packet to the OpenBTS SIP port.

testcall Command This command is included in the CLI for development purposes, but not supported by Range.

tmsis Command This command displays or clears the TMSI table . tmsis prints the current TMSI table. tmsis clear clears the TMSI table.

version Command Print information on the installed version of OpenBTS.

Shell Commands Any line issued to the CLI starting with ! is processed as shell command (in sh). This feature can be used to execute other applications from inside OpenBTS when only one interface screen is available. Examples follow:

To see the 10 most recent registration attempts, assuming Log.Level.SIPEngine.cpp is set to INFO or lower,
OpenBTS> ! grep Register /var/log/OpenBTS.log | grep IMSI | tail -n 10

To access the local Asterisk console,


OpenBTS> ! sudo asterisk -r

If you then exit the Asterisk shell with quit, you will return to the OpenBTS CLI. *********************************

If you don't, check out the common errors: libusrp-3.4.2.so.0: cannot open shared object file: No such file or directory The problem is that your system cannot find the needed library (libusrp-3.4.2.so.0 in this case). The way to remedy this is by adding the file location (/usr/local/lib for gnuradio) to the /etc/ld.so.conf file, as shownhere: [ http://ubuntuforums.org/showthread.php?t=420008 ]. Follow this by updating the ldcache: sudo ldconfig

virtual bool usrp_standard_tx::set_tx_freq(int, double): Assertion `dac_rate () == 128000000' failed. This means you have the wrong version of gnuradio installed. Make sure you get a version > 3.3

bind() failed: Address already in use This means there is a stray transceiver process. You'll need to kill it to free up the needed port. [dburgess@localhost apps]$ ps PID TTY TIME CMD

23233 pts/1 00:00:00 bash 23342 pts/1 00:00:32 transceiver 23369 pts/1 00:00:00 ps [dburgess@localhost apps]$ kill -KILL 23342

USRPDevice.cpp:353: WARNING -- UNDERRUN in TRX->USRP interface Problem: The software is not feeding transmitted data to the radio fast enough to keep up with real time. An occasion underrun is OK, but more than a few every few minutes will make your system unusable.

Solution(s):

Try running the transceiver and OpenBTS under nice to improve priority. Kill other applications to free up CPU resources and reduce swapping. Get a faster computer. A 1.6 GHz single-core Intel should be adequate, though.

Transceiver.cpp:519: RX failed to tune TRXManager.cpp:357: RXTUNE failed with status 1 TRXManager.cpp:409: POWERON failed with status 1 TRXManager.cpp:422: SETPOWER failed with status 1 Problem: You may be running the wrong transceiver program for your USRP hardware. For a Range Networks radio, use TransceiverRAD1. For Ettus boxes (w/ 52mhz clock), use Transceiver52M. We no longer support 64 mhz (the default USRP1) clocks. ***********************************************

Build and Install Smqueue


Smqueue is the store-and-forward message service packaged with OpenBTS. Building and running is very similar to the process used for OpenBTS. Building Smqueue In the smqueue/trunk directory, run the following commands: autoreconf -i ./configure make You should now have an smqueue executable in the smqueue/trunk/smqueue directory. Configuring Smqueue Similar to OpenBTS, Smqueue also depends on a configuration file, located at /etc/OpenBTS/smqueue.db. Smqueue creates an empty, nonfunctional version of this db if it is not available. That's of no use to anyone. Instead, do as we did with OpenBTS and run the following command:

(from the smqueue directory)

sudo sqlite3 -init smqueue/smqueue.example.sql /etc/OpenBTS/smqueue.db That will initialize /etc/OpenBTS/smqueue.db with default values. These configuration variables should work without modification, and are listed here:

*****************************

Log.Level - Default logging level when no other level is defined for a file. Log.Level.smcommands.cpp - Log level for short codes. Log.Alarms.Max - Maximum number of alarms to remember inside the application. Asterisk.address - The Asterisk/SIP PBX IP address. SIP.myPort - The port that smqueue should bind to. SIP.myIP - The internal IP address. Usually 127.0.0.1. SIP.myIP2 - The external IP address that is communciated to the SIP endpoints. SIP.Proxy.Registration - The IP host and port of the proxy to be used for registration and authentication. This is OpenRegistry, for example. Debug.print_as_we_validate SIP.GlobalRelay.IP - IP address of global relay to send unresolvable messages to. NULL disables the gateway. SIP.GlobalRelay.Port - Port of global relay to send unresolvable messages to. SIP.GlobalRelay.ContentType - The content type that the global relay expects. text/plain and application/vnd.3gpp.sms are the only valid options. SMS.FakeSrcSMSC - Use this to fill in L4 SMSC address in SMS delivery. savefile - The file to save SMS messages to when exiting. Bounce.Code - The short code that bounced messages originate from. Bounce.Message.IMSILookupFailed - The Bounce message that is sent when the originating IMSI cannot be verified. Bounce.Message.NotRegistered - Bounce message indicating that the destination phone is not regsitered. SC.Register.Code SC.Register.Msg.WelcomeA SC.Register.Msg.WelcomeB SC.Register.Msg.AlreadyA SC.Register.Msg.AlreadyB SC.Register.Msg.TakenA SC.Register.Msg.TakenB SC.Register.Msg.ErrorA SC.Register.Msg.ErrorB SC.Register.Digits.Max SC.Register.Digits.Min SC.Register.Digits.Override SC.Info.Code

SC.DebugDump.Code SC.QuickChk.Code SC.ZapQueued.Code SC.ZapQueued.Password SC.WhiteList.Code SC.WhiplashQuit.Code SC.WhiplashQuit.Password SC.WhiplashQuit.SaveFile SC.Email.Code SC.Email.MailCommand - The command to execute to send emails. SC.Email.DefaultSubj - Default subject for email messages. SC.Email.Domain - Email message origination domain. SC.Email.ContentType - The default content type of email message.s SC.Email.Header - The header attached to email messages. SC.Email.Footer - Footer attached to email messagess. SubscriberRegistry.A3A8 - Location of the program that encrypts RAND and Ki SubscriberRegistry.HTTP.Server - URL of the subscriber registry server. SubscriberRegistry.db - The location of the sqlite3 database holding the subscriber registry. SC.SMSC.Code - The SMSC entry point. There is where OpenBTS sends SIP MESSAGES to.

********************************

Running Smqueue Smqueue is run with the following command: (from the smqueue directory) cd smqueue sudo ./smqueue Smqueue does not have a command-line interface, instead just reading configuration values and processing messages. Remember, if you change any of the variables, you'll need to restart smqueue for the changes to take effect.

Selecting and Configuring a PBX


There are two primary open-source PBX/Soft switches available. These are Asterisk : http://www.asterisk.org/downloads and FreeSwitch: http://www.freeswitch.org/ . The differences, tradeoffs, and advantages to using one system over the other are too numerous and outside the scope of this document. However, the key point is that both are actively supported and used by the OpenBTS community. Asterisk is the "standard" OpenBTS PBX and is shipped in the commercial units. It's the easiest to set up, most documented, and generally simplest option. The steps for installing and configuring Asterisk to work with OpenBTS are explained in next sections. FreeSwitch is an up-and-coming Asterisk competitor. Its interoperation with OpenBTS is supported primarily by the group at Berkeley. It provides programmatic voice and text routing, as well as a more flexible programming environment for voice/sms applications at the cost of being buggier, harder to set up, and having less support. The steps for installing and configuring FreeSwitch to work with OpenBTS are explained later in this document.

Build and Install the Subscriber Registry and Sipauthserve


Subscriber Registry In the svn repository there is a sql file that you need to create the Subscriber Registry. It is located at: public/subscriberRegistry/trunk/configFiles/subscriberRegistryInit.sql To setup the Subscriber Registry database run: sudo mkdir /var/lib/asterisk/sqlite3dir sudo sqlite3 -init subscriberRegistryInit.sql /var/lib/asterisk/sqlite3dir/sqlite3.db

Sipauthserve
Sipauthserve is an aptly-named daemon providing SIP authentication services. The SIP.Proxy.Registration config variable in openbts should point to its hostname and port.To build Sipauthserve, you MUST HAVE ALREADY BUILT OPENBTS. This is a makefile hack, and will hopefully be fixed at some point in the future.

To build Sipauthserve: (from svn root) cd subscriberRegistry/trunk make This will produce a sipauthserve executable. As with smqueue and OpenBTS, you'll need to configure sipauthserve. We assume /etc/OpenBTS/ already exists. (from subscriberRegistry root) sqlite3 -init sipauthserve.example.sql /etc/OpenBTS/sipauthserve.db

RRLP Server
Build and Install the CGIs Running It All Now run each individual executable in a separate terminal/window. These would be: openbts/trunk/apps/OpenBTS smqueue/trunk/smqueue/smqueue subscriberRegistry/trunk/sipauthserve Then turn on a phone with a GSM SIM card installed. It would be best if this SIM was NOT from a local carrier; then the phone will not immediately camp to one of their towers in the area. In most cases, on most phones, there is a way to select the specific network you wish to attach to. For this basic install, the network will be announced as: 001 01. Connect to that network. Your BTS should reply, allowing the phone to associate. If this fails, make sure you set the Control.LUR.OpenRegistration variable in OpenBTS.db. With these two tests passed, you can now test the connection. Call 600 from the phone (9196 with FreeSWITCH) to call the "echo" service. If that's working, congrats!

Ways to install GNU Radio


There are two ways to install GNU Radio: either by using pre-compiled binary packages, or manually compiling it from source. Most Linux distributions provide binary packages through their regular repositories, and this is generally the easiest and fastest way to get a running system. The development of GNU Radio is extremely fast-paced, however, and binaries provided by your favourite distribution are most likely outdated. If you want any of the following:

...the most up-to-date code ...to closely follow the development of GNU Radio ...to modify GNU Radio yourself.

... you will most likely want to install GNU Radio from source. For Fedora and Ubuntu users, there is a script which does all the heavy lifting. For other distributions, you will have to run through the install process manually.

Using pre-compiled binaries NOTE: pre-compiled binaries are very old, and new versions are no longer putting into the standard repositories for apt-get and yum installationbut there will be support for this in the near future. Meanwhile, please follow the instructions for building from source or using the buildgnuradio script (see next two sections). Pre-compiled binaries come packaged with your distribution. On Ubuntu, installing GNU Radio from binaries is as easy as calling $ apt-get install gnuradio On Fedora, run $ yum install gnuradio

Using the build-gnuradio script The build-gnuradio is an install script for recent Fedora and Ubuntu systems provided by Marcus Leech: http://www.sbrac.org/files/build-gnuradio

It downloads and installs all dependencies, downloads both UHD and GNU Radio from git (which means it will automatically install the latest version from the 'main' branch), runs the make process and installs it on your system. In most cases, simply running the script will do all you need to get a running GNU Radio system built from source. Also, you still have all the source code lying on your hard disk and therefore available for future modifications. It combines the flexibility of installing from source with the ease of using binaries and is recommended for most users of Ubuntu and Fedora. Download the script from http://www.sbrac.org/files/build-gnuradio. Save it wherever you want the GNU Radio source code to be copied to (or copy it somewhere into your $PATH). You might have to give it executable permissions by running $ chmod a+x build-gnuradio Then, simply call the script by $ ./build-gnuradio That's it!Thanks to Marcus Leech for putting this together and hosting it.

******************************
#!/bin/bash # # Build script for UHD+GnuRadio on Fedora and Ubuntu # # # function help { cat <<!EOF! Usage: build-gnuradio [--help|-h] [-v|--verbose] [-jN] [-ja] [-l|--logfile logfile ] [-u|--users ulist] funcs -v|--verbose - turn on verbose logging to stdout -jN -ja -josh - have make use N concurrent jobs - have make use N concurrent jobs with auto setting of N (based on number of cpu cores on build system) - use Josh Blums enhanced Gnu Radio GIT repo

-u|--users ul - add comma-separated users to 'usrp' group in addition to calling user ( $USER ) -l|--logfile lf - log messages to 'lf' -a|--autotools - do a traditional auto-tools build -ut -gt <tag> <tag> - set tag for UHD checkout to <tag> - set tag for Gnu Radio checkout to <tag>

available funcs are: all - do all functions

prereqs - install prerequisites gitfetch - use GIT to fetch Gnu Radio and UHD uhd_build - build only UHD firmware - fetch firmware/FPGA gnuradio_build - build only Gnu Radio mod_groups - modify the /etc/groups and add user to group 'usrp' mod_udev - add UDEV rule for USRP1 mod_sysctl - modify SYSCTL for larger net buffers !EOF! } if [ $USER = root -o $UID -eq 0 ] then echo Please run this script as an ordinary user echo it will acquire root privileges as it needs them via \"sudo\". exit fi VERBOSE=No JFLAG="" LOGDEV=/dev/null USERSLIST=None JOSHMODE=False UTAG=None GTAG=None while : do case $1 in -ja) cnt=`grep 'processor.*:' /proc/cpuinfo|wc -l` cnt=`expr $cnt - 1` if [ $cnt -lt 1 ] then cnt=1 fi JFLAG=-j$cnt shift ;; -j[123456789]) JFLAG=$1 shift ;; -josh) JOSHMODE=True shift ;; -v|--verbose) LOGDEV=/dev/stdout shift ;; -l|--logfile) case $2 in /*) LOGDEV=$2 ;; *) LOGDEV=`pwd`/$2 ;; esac shift shift rm -f $LOGDEV echo $LOGDEV Starts at: `date` >>$LOGDEV 2>&1 ;;

-u|--users) USERSLIST=$2 shift shift ;; -a|--autotools) CMAKE_GNUBUILD=False shift ;; -h|--help) help exit ;; -ut) UTAG=$2 shift shift ;; -gt) GTAG=$2 shift shift ;; -*) echo Unrecognized option: $1 echo help exit break ;; *) break ;; esac done CWD=`pwd` SUDOASKED=n SYSTYPE=unknown if [ -f /etc/fedora-release -o -f /etc/lsb-release ] then good_to_go=yes else echo You appear to not be running on a Fedora or Ubuntu system. echo This script will only run correctly on a Fedora or Ubuntu system. echo Exiting. exit fi echo This script will install Gnu Radio from current GIT sources echo You will require Internet access from the computer on which this echo script runs. You will also require SUDO access. You will require echo approximately 500MB of free disk space to perform the build. echo " " echo This script will, as a side-effect, remove any existing Gnu Radio echo installation that was installed from your Linux distribution packages. echo It must do this to prevent problems due to interference between echo a linux-distribution-installed Gnu Radio/UHD and one installed from GIT source. echo " " echo The whole process may take up to two hours to complete, depending on the echo capabilities of your system. echo -n Proceed? read ans case $ans in

y|yes|Y|YES|Yes) PROCEED=y ;; *) exit esac SPACE=`df $HOME| grep -v blocks|grep '%'` SPACE=`echo $SPACE | awk '/./ {n=NF-2; printf ("%d\n", $n/1.0e3)}'` if [ $SPACE -lt 500 ] then echo "You don't appear to have enough free disk space on $HOME" echo to complete this build/install echo exiting exit fi total=0 for file in uhd.20* gnuradio.20* do if [ -d $file ] then sz=`du -s $file|awk '{print $1}'` total=`expr $total + $sz` fi done total=`expr $total '*' 1024` total=`expr $total / 1000000` if [ $total -gt 400 ] then echo Your old 'uhd.*' and 'gnuradio.*' directories are using roughly $total MB echo of disk space: ls -ld uhd.20* gnuradio.20* echo " " echo -n Remove them'?' read ans case $ans in yes|YES) echo removing uhd.20* and gnuradio.20* rm -rf uhd.20* gnuradio.20* echo Done ;; esac fi function my_echo { if [ $LOGDEV = /dev/stdout ] then echo $* else echo $* echo $* >>$LOGDEV 2>&1 fi } function checkcmd { which $1 >tmp$$ 2>&1 if grep -q no.${1}.in tmp$$ then my_echo Failed to find command \'$1\' after pre-requisite installation. my_echo This very likely indicates that one or more parts of the my_echo pre-requisite installation has failed. rm -f tmp$$ my_echo -n Show pre-requisites install log? read ans case $ans in y|Y|Yes|yes|YES) more prereq.log

;; esac #rm -f prereq.log rm -f tmp$$ my_echo exiting build exit fi rm -f tmp$$ } function checklib { found=0 my_echo -n Checking for library $1 ... for dir in /lib /usr/lib /usr/lib64 /lib64 do ls -l $dir/${1}*.so* >tmp$$ 2>&1 if grep -q "\\*.so\\*:" tmp$$ then found=0 else found=1 if [ $2 -gt 0 ] then NL=`cat tmp$$|wc -l` if [ $NL -lt $2 ] then found=0 fi fi break fi rm -f tmp$$ done if [ $found -le 0 ] then my_echo "*******" my_echo Failed to find libraries with prefix \'$1\' after pre-requisite installation. my_echo This very likely indicates that the pre-requisite installation failed my_echo to install one or more critical pre-requisites for Gnu Radio/UHD my_echo -n Show pre-requisites install log? read ans case $ans in y|Y|yes|Yes|YES) more prereq.log ;; esac #rm -rf prereq.log my_echo exiting build exit else my_echo Found library $1 fi } function checkpkg { my_echo Checking for package $1 if [ `apt-cache search $1 | wc -l` -eq 0 ] then my_echo Failed to find package \'$1\' in known packages my_echo Perhaps you need to add the Ubuntu universe or multiverse PPA? my_echo see https://help.ubuntu.com/community/Repositories/Ubuntu #rm -rf prereq.log my_echo exiting build exit fi } function prereqs { sudocheck my_echo -n Installing pre-prequisites...

# # Check whether we're on a Fedora or Ubuntu system, and "do the right thing" # for either system # # It's a Fedora system # if [ -f /etc/fedora-release ] then SYSTYPE=Fedora case `cat /etc/fedora-release` in *12*|*13*|*14*|*15*) sudo yum -y erase 'gnuradio*' >>$LOGDEV 2>&1 sudo yum -y erase 'libgruel-*' >>$LOGDEV 2>&1 sudo yum -y erase 'libgruel*' >>$LOGDEV 2>&1 sudo yum -y groupinstall "Engineering and Scientific" "Development Tools" >>$LOGDEV 2>&1 sudo yum -y install fftw-devel cppunit-devel wxPython-devel libusb-devel \ guile boost-devel alsa-lib-devel numpy gsl-devel python-devel pygsl \ python-cheetah python-lxml guile-devel PyOpenGL qt-devel qt qt4 qt4-devel \ PyQt4-devel qwt-devel qwtplot3d-qt4-devel libusb libusb-devel \ libusb1 libusb1-devel cmake git wget sdcc python-docutils \ PyQwt PyQwt-devel qwt-devel >>$LOGDEV 2>&1 ;; *) my_echo Your Fedora system release must be at least release 12 to proceed exit ;; esac # # It's a Ubuntu system # elif [ -f /etc/lsb-release ] then SYSTYPE=Ubuntu sudo apt-get -y purge 'gnuradio-*' >>$LOGDEV 2>&1 sudo apt-get -y purge 'libgruel-*' >>$LOGDEV 2>&1 sudo apt-get -y purge 'libgruel*' >>$LOGDEV 2>&1 sudo apt-get -y purge 'libgruel0*' >>$LOGDEV 2>&1 sudo apt-get -y purge 'libgnuradio*' >>$LOGDEV 2>&1 sudo apt-get -y purge 'python-gnuradio*' >>$LOGDEV 2>&1 case `grep DISTRIB_RELEASE /etc/lsb-release` in *11.*) PKGLIST="libfontconfig1-dev libxrender-dev libpulse-dev swig g++ automake autoconf libtool python-dev libfftw3-dev libcppunit-dev libboost-all-dev libusb-dev libusb-1.0-0-dev fort77 sdcc sdcc-libraries libsdl1.2-dev python-wxgtk2.8 git-core guile-1.8-dev libqt4-dev python-numpy ccache python-opengl libgsl0-dev python-cheetah python-lxml doxygen qt4-dev-tools libusb-1.0-0-dev libqwt5-qt4-dev libqwtplot3d-qt4-dev pyqt4-dev-tools python-qwt5-qt4 cmake git-core wget sdcc libxi-dev python-docutils" ;; *10.04*|*10.10*) PKGLIST="libfontconfig1-dev libxrender-dev libpulse-dev swig g++ automake autoconf libtool python-dev libfftw3-dev libcppunit-dev libboost-all-dev libusb-dev libusb-1.0-0-dev fort77 sdcc sdcc-libraries libsdl1.2-dev python-wxgtk2.8 git-core guile-1.8-dev libqt4-dev python-numpy ccache python-opengl libgsl0-dev python-cheetah python-lxml doxygen qt4-dev-tools libusb-1.0-0-dev libqwt5-qt4-dev libqwtplot3d-qt4-dev pyqt4-dev-tools python-qwt5-qt4 cmake git-core wget sdcc python-docutils" ;; *9.10*) PKGLIST="swig g++ automake autoconf libtool python-dev libfftw3-dev libcppunit-dev libboost1.38-dev libusb-dev libusb-1.0-0-dev fort77 sdcc sdcc-libraries libsdl1.2-dev python-wxgtk2.8 git-core guile-1.8-dev libqt4-dev python-numpy ccache python-opengl libgsl0-dev python-cheetah python-lxml doxygen qt4-dev-tools libusb-1.0-0-dev libqwt5-qt4-dev libqwtplot3d-qt4-dev pyqt4-dev-tools

cmake git wget sdcc python-docutils" ;; *9.04*) sudo apt-get purge python-wxgtk2.6 PKGLIST="swig g++ automake1.9 autoconf libtool python-dev fftw3-dev libcppunit-dev libboost1.35-dev sdcc-nf libusb-dev libusb-1.0-0-dev libsdl1.2-dev python-wxgtk2.8 git-core guile-1.8-dev libqt4-dev python-numpy ccache python-opengl libgsl0-dev python-cheetah python-lxml doxygen qt4-dev-tools libqwt5-qt4-dev libqwtplot3d-qt4-dev pyqt4-dev-tools cmake git wget python-docutils" ;; *) my_echo Your Ubuntu release must be at least 9.04 to proceed exit ;; esac for pkg in $PKGLIST; do checkpkg $pkg; done sudo apt-get -y install $PKGLIST >>$LOGDEV 2>&1 else my_echo This script supports only Ubuntu and Fedora systems my_echo Your Fedora system must be at least Fedora 12 my_echo Your Ubuntu system must be at least Ubuntu 9.04 exit fi PATH=$PATH:/usr/libexec/sdcc export PATH checkcmd sdcc checkcmd guile checkcmd git checkcmd cmake if [ $SYSTYPE = Fedora ] then checklib libusb-0 0 checklib libusb-1 0 else checklib libusb 2 fi checklib libboost_ 5 checklib libcppunit 0 checklib libguile 5 checklib libfftw 5 checklib libgsl 0 #rm -f prereq.log my_echo Done } function gitfetch { date=`date +%Y%m%d%H%M%S` # # Check for existing gnuradio directory # if [ $JOSHMODE = False ] then if [ -d gnuradio ] then mv gnuradio gnuradio.$date fi else if [ -d jblum ]

then mv jblum jblum.$date fi fi # # Check for existing UHD directory # if [ -d uhd ] then mv uhd uhd.$date fi # # GIT the gnu radio source tree # my_echo -n Fetching Gnu Radio via GIT... if [ $JOSHMODE = False ] then git clone --progress http://gnuradio.org/git/gnuradio.git >>$LOGDEV 2>&1 if [ ! -d gnuradio/gnuradio-core ] then my_echo GIT checkout of Gnu Radio failed! exit fi if [ $GTAG != None ] then cd gnuradio git checkout $GTAG >/dev/null 2>&1 git status >tmp$$ 2>&1 if grep -q "On branch $GTAG" tmp$$ then whee=yes rm -f tmp$$ else my_echo Could not fetch Gnu Radio tagged $GTAG from GIT rm -f tmp$$ exit fi cd .. fi else git clone --progress git://gnuradio.org/jblum.git >>$LOGDEV 2>&1 if [ ! -d jblum/gnuradio-core ] then my_echo GIT checkout of Gnu Radio from jblum.git failed! exit fi fi my_echo Done # # GIT the UHD source tree # rm -rf uhd my_echo -n Fetching UHD via GIT... git clone --progress git://code.ettus.com/ettus/uhd.git >>$LOGDEV 2>&1 if [ ! -d uhd/host ] then my_echo GIT checkout of UHD using GIT protocol failed...trying my_echo with http instead rm -rf UHD-Mirror git clone --progress http://github.com/EttusResearch/UHD-Mirror.git >>$LOGDEV 2>&1 if [ ! -d UHD-Mirror/host ] then my_echo GIT check of UHD using http protocol failed--exiting exit fi mv UHD-Mirror uhd

fi if [ $UTAG != None ] then cd uhd git checkout $UTAG >/dev/null 2>&1 git status >tmp$$ 2>&1 if grep -q "On branch $UTAG" tmp$$ then whee=yes rm -f tmp$$ else my_echo Could not fetch UHD tagged $UTAG from GIT rm -f tmp$$ fi cd .. fi my_echo Done } function uhd_build { # # UHD build # sudocheck if [ ! -d uhd ] then my_echo you do not appear to have the \'uhd\' directory my_echo you should probably use $0 gitfetch to fetch the appropriate my_echo files using GIT exit fi if [ $UTAG != None ] then cd uhd git checkout $UTAG >/dev/null 2>&1 cd .. fi my_echo -n Building UHD... cd uhd/host if [ ! -d build ] then mkdir build fi cd build make clean >/dev/null 2>&1 cmake ../ >>$LOGDEV 2>&1 make clean >>$LOGDEV 2>&1 make $JFLAG >>$LOGDEV 2>&1 if [ $? -ne 0 ] then my_echo UHD build apparently failed my_echo Exiting UHD build exit fi sudo make $JFLAG install >>$LOGDEV 2>&1 if [ ! -f /usr/local/bin/uhd_find_devices ] then my_echo UHD build/install apparently failed my_echo Exiting UHD build exit fi sudo ldconfig >>$LOGDEV 2>&1 my_echo Done building/installing UHD } function firmware { sudocheck # # Firmware/FPGA images...

# my_echo Fetching and installing FPGA/Firmware images via wget... rm -rf wget-tmp* mkdir wget-tmp$$ cd wget-tmp$$ # # Fetch the tar file # UHD_IMG_PREFIX=http://files.ettus.com/uhd_releases/master_images fn=NOTEXIST # # Try for any .tar.gz files # wget http://files.ettus.com/uhd_releases/master_images/auto/current.tar.gz >/dev/null 2>&1 xx=`ls *.gz|sort|tail -1` if [ "@@" != @${xx}@ ] then fn=$xx fi if [ $fn = NOTEXIST ] then my_echo Failed to download any usable images file from: $UHD_IMG_PREFIX exit fi # # Check to make sure we got it # if [ ! -f $fn ] then my_echo Failed to fetch $fn: with latest UHD firmware/fpga images exit fi # # Now unpack the tar file # my_echo ...Installing from: $fn tar xf $fn if [ ! -d UHD*/share/uhd/images ] then my_echo There was a problem with the TAR file: $fn my_echo The appropriate directories were not unpacked from it my_echo In particular, UHD.../share/uhd/images does not exist exit fi # # There's now a directory structure from the tar file # Descend into it and copy the images to /usr/local/share/uhd/images # cd UHD*/share/uhd/images if [ ! -d /usr/local/share/uhd/images ] then sudo mkdir -p /usr/local/share/uhd/images fi my_echo ...Copying into /usr/local/share/uhd sudo cp *.bin /usr/local/share/uhd/images sudo cp *.ihx /usr/local/share/uhd/images sudo cp *.rbf /usr/local/share/uhd/images sudo cp *.tag /usr/local/share/uhd/images sudo chmod 644 /usr/local/share/uhd/images/* cd $CWD rm -rf wget-tmp$$

my_echo Done } function gnuradio_build { sudocheck if [ $JOSHMODE = False ] then if [ ! -d gnuradio ] then my_echo you do not appear to have the \'gnuradio\' directory my_echo you should probably use $0 gitfetch to fetch the appropriate my_echo files using GIT exit fi if [ $GTAG != None ] then cd gnuradio git checkout $GTAG >/dev/null 2>&1 cd .. fi else if [ ! -d jblum ] then my_echo you do not appear to have the \'jblum\' directory my_echo you should probably use $0 gitfetch to fetch the appropriate my_echo files using GIT exit fi fi # # LD stuff # my_echo /usr/local/lib >tmp$$ my_echo /usr/local/lib64 >>tmp$$ if grep -q /usr/local/lib /etc/ld.so.conf.d/* then my_echo /usr/local/lib already in ld.so.conf.d else sudo cp tmp$$ /etc/ld.so.conf.d/local.conf fi rm -f tmp$$ my_echo Doing ldconfig... sudo ldconfig >/dev/null 2>&1 PKG_CONFIG_PATH=/usr/local/lib/pkgconfig if [ -d /usr/local/lib64/pkgconfig ] then PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig fi export PKG_CONFIG_PATH # # Build Gnuradio # if [ $JOSHMODE = False ] then cd gnuradio else cd jblum git checkout gr_basic >>$LOGDEV 2>&1 fi if [ $CMAKE_GNUBUILD = True ] then my_echo Building Gnu Radio... my_echo ...Doing cmake

if [ -d build ] then my_echo ...build directory already here else mkdir build fi cd build make clean >/dev/null 2>&1 my_echo ...Cmaking cmake ../ >>$LOGDEV 2>&1 my_echo ...Building make $JFLAG clean >>$LOGDEV 2>&1 make $JFLAG >>$LOGDEV 2>&1 if [ $? -ne 0 ] then my_echo make failed my_echo Exiting Gnu Radio build/install exit fi else my_echo ..Traditional autotools build my_echo ...Boostrapping ./boostrap >>$LOGDEV 2>&1 my_echo ...Configuring ./configure >>$LOGDEV 2>&1 my_echo ...Building make >>$LOGDEV 2>&1 fi my_echo ...Installing sudo make $JFLAG install >>$LOGDEV 2>&1 sudo ldconfig >>$LOGDEV 2>&1 my_echo Done building and installing Gnu Radio my_echo -n GRC freedesktop icons install ... if [ -f /usr/local/libexec/gnuradio/grc_setup_freedesktop ] then sudo chmod 755 /usr/local/libexec/gnuradio/grc_setup_freedesktop sudo /usr/local/libexec/gnuradio/grc_setup_freedesktop install >>$LOGDEV 2>&1 fi my_echo Done } function mod_groups { sudocheck # # Post install stuff # # USRP rules for UDEV and USRP group # # # Check for USRP group, and update if necessary if grep -q usrp /etc/group then my_echo Group \'usrp\' already in /etc/group else sudo /usr/sbin/groupadd usrp fi # # Check that our calling user is in the USRP group, update if necessary # if grep -q usrp.*${USER} /etc/group then my_echo User $USER already in group \'usrp\' else sudo /usr/sbin/usermod -a -G usrp $USER cat <<"!EOF!" ******************************************************************************** This script has just modified /etc/group to place your userid '('$USER')' into group 'usrp' In order for this change to take effect, you will need to log-out and log back in again. You will not be able to access your USRP1 device until you do this.

If you wish to allow others on your system to use the USRP1 device, you will need to use: sudo usermod -a -G usrp userid For each userid you wish to allow access to the usrp ******************************************************************************** Further !EOF! fi if [ "$USERSLIST" = None ] then foo=bar else ul=`echo $USERSLIST|sed -e 's/,/ /g'` for u in $ul do sudo /usr/sbin/usermod -a -G usrp $u my_echo Added $u to group usrp done fi } function mod_udev { sudocheck # # Check for UDEV rules file, update if necessary # if [ ! -f /etc/udev/rules.d/10-usrp.rules ] then if [ -f $CWD/uhd/host/utils/uhd-usrp.rules ] then cp $CWD/uhd/host/utils/uhd-usrp.rules tmp$$ else cat >>tmp$$ <<"!EOF!" # # Copyright 2011 Ettus Research LLC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ACTION=="add", BUS=="usb", SYSFS{idVendor}=="fffe", SYSFS{idProduct}=="0002", MODE:="0666" ACTION=="add", BUS=="usb", SYSFS{idVendor}=="2500", SYSFS{idProduct}=="0002", MODE:="0666" !EOF! fi chmod 644 tmp$$ sudo mv tmp$$ /etc/udev/rules.d/10-usrp.rules sudo killall -HUP udevd sudo udevadm control --reload-rules rm -f tmp$$ else my_echo USRP rules for UDEV already in place fi } function mod_sysctl { sudocheck

# # Modify sysctl.conf as necessary # cat >tmp$$ <<!EOF! # Updates for Gnu Radio net.core.rmem_max = 1000000 net.core.wmem_max = 1000000 kernel.shmmax = 2147483648 !EOF! if grep -q 'Updates for Gnu Radio' /etc/sysctl.conf then my_echo Required updates to /etc/sysctl.conf already in place else my_echo Applying updates to /etc/sysctl.conf cat /etc/sysctl.conf tmp$$ >tmp2$$ chmod 644 tmp2$$ sudo mv tmp2$$ /etc/sysctl.conf fi sudo sysctl -w net.core.rmem_max=1000000 >/dev/null 2>&1 sudo sysctl -w net.core.wmem_max=1000000 >/dev/null 2>&1 sudo sysctl -w kernel.shmmax=2147483648 >/dev/null 2>&1 rm -f tmp$$ rm -f tmp2$$ if grep -q usrp /etc/security/limits.conf then my_echo usrp group already has real-time scheduling privilege else cat >tmp$$ <<!EOF! @usrp - rtprio 50 !EOF! cat /etc/security/limits.conf tmp$$ >tmp2$$ sudo cp tmp2$$ /etc/security/limits.conf sudo chmod 644 /etc/security/limits.conf rm -f tmp$$ tmp2$$ my_echo Group \'usrp\' now has real-time scheduling privileges my_echo You will need to log-out and back in again for this to my_echo take effect fi } function all { my_echo Starting all functions at: `date` cd $CWD prereqs touch -d "15 minutes ago" touch$$ if [ -d uhd -a -d gnuradio ] then if [ uhd -ot touch$$ -o gnuradio -ot touch$$ ] then gitfetch else my_echo Skipping git fetch, since \'uhd\' and \'gnuradio\' are new enough fi else gitfetch fi rm -f touch$$ for fcn in uhd_build firmware gnuradio_build mod_groups mod_udev mod_sysctl pythonpath do my_echo Starting function $fcn at: `date` cd $CWD $fcn my_echo Done function $fcn at: `date` done my_echo Done all functions at: `date`

} function pythonpath { for PYVER in 2.6 2.7 do for type in "" 64 do if [ -d /usr/local/lib${type}/python${PYVER}/site-packages/gnuradio ] then PYTHONPATH=/usr/local/lib${type}/python${PYVER}/site-packages fi if [ -d /usr/local/lib/${type}/python${PYVER}/dist-packages/gnuradio ] then PYTHONPATH=/usr/local/lib${type}/python${PYVER}/dist-packages fi done done echo echo echo "************************************************************" echo You should probably set your PYTHONPATH to: echo " " echo " " $PYTHONPATH echo " " echo in your .bashrc or equivalent file prior to attempting to run echo any Gnu Radio applications or Gnu Radio Companion. echo "*************************************************************" } function sudocheck { # # Check SUDO privileges # if [ $SUDOASKED = n ] then echo SUDO privileges are required echo -n Do you have SUDO privileges'?' read ans case $ans in y|yes|YES|Y) echo Continuing with script SUDOASKED=y sudo grep timestamp_timeout /etc/sudoers >tmp$$ timeout=`cat tmp$$|awk '/./ {print $4}'` rm -f tmp$$ if [ "@@" = "@$timeout@" ] then sudo cp /etc/sudoers tmp$$ sudo chown $USER tmp$$ sudo chmod 644 tmp$$ echo "Defaults timestamp_timeout = 90" >>tmp$$ sudo cp tmp$$ /etc/sudoers sudo chown root /etc/sudoers sudo chmod 440 /etc/sudoers elif [ $timeout -lt 90 ] then echo You need to have a timestamp_timout in /etc/sudoers of 90 or more echo Please ensure that your timestamp_timeout is 90 or more exit fi ;; *) echo Exiting. Please ensure that you have SUDO privileges on this system! exit ;; esac fi }

PATH=$PATH:/usr/libexec/sdcc export PATH CMAKE_GNUBUILD=True case $# in 0) all my_echo All Done exit esac for arg in $* do cd $CWD $arg done my_echo All Done

**********************************

Installing manually from source


If you choose this route, you have slightly more work to do. First, you need to download(http://gnuradio.org/redmine/projects/gnuradio/wiki/Download ) the code. You can get the code as a tarball or check it out from the git repository. To build GNU Radio, refer to the build guide. If you want to be able to use USRP devices, you need to install UHD before installing GNU Radio. To build gnuradio manually first Get the source code: http://gnuradio.org/redmine/projects/gnuradio/wiki/Download

Then: Start the build process To compile, there are 5 steps. Start by cd'ing to the gnuradio directory, then complete the following commands: $ ./bootstrap # Do NOT perform this step if you are building from a tarball. $ ./configure $ make $ make check $ sudo make install This will perform all configuration checks and select for build, test, and installation all components that pass. For finer control, read the instructions at BuildConfiguration. ****************************************

The GNU Radio Build Configuration System The GNU Radio source code build system uses the standard method: $ ./configure $ make $ sudo make install

or using an alternate build directory: $ mkdir build $ cd build $ ../configure $ make $ sudo make install to build and install the software. This is a sufficient starting point for most users. GNU Radio consists of a set of component libraries, simply called "components" in what follows. component libraries consists base system,hardware support,audio device support , graphic support ,general signal processing , specialty application area, Deprecated. For more information refer to : http://gnuradio.org/redmine/projects/gnuradio/wiki/Components Each component lives in a separate directory off the source code tree root, and has a set of prerequisites for which the 'configure' script tests. Depending on the outcome of these configuration checks, the build system either selects or deselects individual components to build, test, and install. The default behavior is to perform all configuration tests, build all components that pass, and ignore the ones that don't. Some users may wish to have finer control over what gets built and what does not, and the build system provides a facility to accomplish that. The build system also allows for incremental installation of individual components.

Build System Configuration Options Three options exist for each component in the GNU Radio source code tree: --enable-foo --disable-foo --with-foo[=arg] where foo is the directory name of the component to be affected, and for the last option arg is the full path to the pkg-config file for foo ('foo.pc'). There are also: --enable-all-components --disable-all-components These apply to all components in the tree that are not further specified on the configure script command line.

Default Behavior Controlling individual components using --enable-foo, --disable-foo, and --with-foo[=arg] Specifying --enable-foo causes the build system to consider it an error if configuration checks fail for the foo component, and exit with an error when that happens ('error out'). This option is suitable for ensuring that a particular component gets built and installed, or for understanding why configure errored out when the checks fail. Specifying --disable-foo prevents that component from being built or installed even if its configuration checks pass. This option is suitable for components that you're not interested in or you know ahead of time won't pass configuration checks. Specifying --enable-all-components or --disable-all-components applies the above behavior to everything that isn't otherwise specified later in the command line. Specifying --with-foo causes the build system to look for the pkg-config file, using the provided PKG_CONFIG_PATH environment variable, for foo as evidence that the component foo is already installed. If foo is not already installed, the an error will be printed and configuration will stop. Significant efforts have been made to ensure that if --with-foo is specified, and foo is installed, then the paths to foo's libraries and header files will not interfere with those from the -enable'd components. Speficying --with-foo=arg is the same as --with-foo, except that component foo is searched for solely using PKG_CONFIG_PATH=arg. NOTE: Specifying both --enable-foo and --with-foo will result in an error. NOTE: When using --with-foo[=arg] : Because the build system uses pkg-config to locate components, PKG_CONFIG_PATH must include the full path (e.g. "/opt/local/lib/pkgconfig") of those packages unless they are installed in the --prefix provided to configure since that path is internally prepended to PKG_CONFIG_PATH. WARNING: It is possible to install components into different --prefix's, and thus to include them as pre-installed using the --with option. The build system will use the first found pkgconfig file for any given pre-installed and --with included component.

Common Use Cases Default Behavior: $ ./configure Select for build and installation everything that passes configuration checks.

Checking for Everything: $ ./configure --enable-all-components Select everything for build and installation, except exit with an error message if any configuration check doesn't pass. This will likely fail for everyone because some platformspecific configuration checks are mutually exclusive (such as the various audio modules for different systems). Selective Build: $ ./configure --enable-all-components \ --disable-foo1 \ --disable-foo2 where foo1 and foo2 are components that will fail and you don't care about, or that you don't want to build regardless. Otherwise you want the build to fail if anything else fails configuration checks. For example, on a Linux system that otherwise has all the build dependent libraries installed: $ ./configure --enable-all-components \ --disable-gr-audio-osx \ --disable-gr-audio-windows \ --disable-gr-audio-oss will ignore the non-Linux platform modules as well as the OSS audio stuff (which would otherwise compile ok). Build Using Pre-Installed Components: $ ./configure --disable-all-components \ --enable-foo1 \ --with-foo2 will try to build component foo1 using just the already-installed library and header files for component foo2 as found by pkg-config in the provided PKG_CONFIG_PATH. Build Using Pre-Installed Components at a Specific Location: $ ./configure --disable-all-components \ --enable-foo1 \ --with-foo2=bar will try to build component foo1 using just the already-installed library and header files for component foo2 as found by pkg-config in PKG_CONFIG_PATH=bar.

"Minimal" Component Builds To select a single component to build and install, use: $ ./configure --disable-all-components \ --enable-foo where foo is a single component directory. This will cause the build to fail if foo doesn't pass configuration checks, and ignore any other packages. WARNING: Individual GNU Radio components generally depend upon other components (such as gnuradio-core) to successfully compile. When using --disable-all-components, each component dependency must be specified via an --enable or --with option. The build system will produce an error if dependencies are not met, and most likely that component build will be skipped. For example, component gr-usrp depends on components usrp and gnuradio-core. The former depends on components omnithread, mblock, and pmt. The latter depends on the component omnithread, which is redundant with the usrp's dependencies. Hence, from a fresh source code build with nothing already installed, one would need to use the following command line in order to try to build gr-usrp: $ ./configure --disable-all-components \ --enable-gr-usrp \ --enable-gnuradio-core \ --enable-usrp \ --enable-pmt \ --enable-mblock \ --enable-omnithread The order of these on the configure command line is not important; the build system knows the proper order in which to build them. As another example, suppose that components usrp (and its dependents) are already installed, via the commands: $ ./configure --disable-all-components \ --enable-usrp \ --enable-pmt \ --enable-mblock \ --enable-omnithread $ make $ sudo make install

Then one could use those pre-installed components and build gr-usrp via the command: $ ./configure --disable-all-components \ --enable-gr-usrp --enable-gnuradio-core \ --with-usrp \ --with-pmt \ --with-mblock \ --with-omnithread Making Distribution Tarballs Regardless of what gets enabled, disabled, or included via --with-foo[=arg], the 'make dist' and 'make distcheck' operations will create a source distribution tarball of the entire collection of components. ********************************** Generating GNURadio Documentation By default, gnuradio will automatically build documentation if doxygen and xmlto programs are installed prior to installing gnuradio, so make sure they are installed in your system. Doxygen is used to build the gnuradio C++ API documentation. The generated documents can be found and browsed at docs/doxygen/html/index.html. The xmlto is used to convert the extra documentation xml files (found in usrp, gr-trellis,..etc folders) to html files.

Operating System Specific Instructions Here is you go into more specific detail for a given operating system, outlining how to fulfill the build prerequisites, any non-standard build steps that must be taken, and general configuration issues. If a given operating system has binary installation packages or another automated way to build GNU Radio, it will be listed here. Linux

Arch Debian Fedora Gentoo Mandriva SuSE Ubuntu

Installing on Arch Linux


Installing on Arch is a bit more difficult than on other distributions (e.g., Ubuntu and Fedora), because Arch typically has the latest-and-greatest versions of packages, and GNURadio hasn't always quite caught up yet. If you want an easy way to install gnuradio on Arch (with the benefit of easy removal and upgrading) see the Installing GNU Radio from AUR.

Python Version GNURadio is not yet compliant with Python3, and will fail to compile as the build scripts will default to the newest version of Python on your system, which is likely Python3 rather than Python2.7. There are a number of ways to fix this - perhaps the easiest is to simply re-symlink the 'python' command to Python2.7 $ sudo rm /usr/bin/python $ sudo ln -s /usr/bin/python2.7 /usr/binpython This is easy to undo if you choose to. Note that this step is required prior to building the PyQWT5 dependency. Handling Dependencies Install the dependencies using pacman:
$ sudo pacman -S fftw wxpython libusb guile swig cppunit boost portaudio sdl gputils alsa-utils python-opengl

In order to use GNURadio's fancy qtgui features, you will need QWT and PyQWT. Unfortunately, GNURadio uses an older version of these software packages which are not compatible with the newest versions - which are the only versions in the pacman repos. As such, you'll want to build and install both of the following AUR packages: QWT5: http://aur.archlinux.org/packages.php?ID=50980 PyQWT5 for QT4: http://aur.archlinux.org/packages.php?ID=29110 Note that both of these packages install to different directories than the newer pacman versions, and thus do not conflict. If you have never built & installed an AUR package before, the AUR wiki page gives excellent instructions.Installing Packages from AUR: https://wiki.archlinux.org/index.php/Arch_User_Repository#Installing_packages

Build gnuradio Now you can unpack and build gnuradio normally ala: (Don't forget to run ./bootstrap if building from the git repository) $ ./configure --with-qwt-incdir=/usr/include/qwt5 --with-qwt-lib=qwt5 $ make $ make check $ sudo make install

Modify your environment $*PATHs You'll need to have these environment variables set in order to run the examples, so you can put these in your ~/.bashrc (or .zshrc, or whatever you use...) PYTHONPATH=/usr/local/lib/python2.7/site-packages PKG_CONFIG_PATH=/usr/local/lib/pkgconfig

Installing GNU Radio from AUR If you don't use yaourt or something of the likes do the following: Go to http://aur.archlinux.org and search for the package "gnuradio-git". Download the tarball (gnuradio-git.tar.gz) on the packages page. $ tar zxf gnuradio-git.tar.gz $ cd gnuradio-git $ makepkg This should build, and leave you with a file like gnuradio-git-20111025-1-x86_64.pkg.tar.xz which you can install via $ sudo pacman -U gnuradio-git-20111025-1-x86_64.pkg.tar.xz Note: In case you run into trouble building GNU radio using AUR leave a message on the AUR page.

Installing GNU Radio on Debian Linux


The official Debian package repository includes GNU Radio 3.2.2 (released in July 2009) in the sid (unstable) distribution : http://packages.debian.org/sid/gnuradio If you want to use a more recent version of GNU Radio, you can complete a source build either through downloading a tarball: http://gnuradio.org/redmine/projects/gnuradio/wiki/Release33Branch or using git to check out the software from development repository : http://gnuradio.org/redmine/projects/gnuradio/wiki/Download

Building from source on Debian Sid (valid for debian sid on 6 june 2011) Install pre-requisites: sudo apt-get install libaudio-dev sudo apt-get -y install libxi-dev sudo apt-get -y install libfontconfig1-dev libxrender-dev libpulse-dev \ swig g++ automake autoconf libtool python-dev libfftw3-dev \ libcppunit-dev libboost-all-dev libusb-dev fort77 sdcc sdcc-libraries \ libsdl1.2-dev python-wxgtk2.8 git-core guile-1.8-dev \ libqt4-dev python-numpy ccache python-opengl libgsl0-dev \ python-cheetah python-lxml doxygen qt4-dev-tools \ libqwt5-qt4-dev libqwtplot3d-qt4-dev pyqt4-dev-tools python-qwt5-qt4 Make sure you're using g++ v4.5: export CXX=g++-4.5 Download GNU Radio from git: git clone http://gnuradio.org/git/gnuradio.git Bootstrap, configure and build: cd gnuradio ./bootstrap ./configure make -e

Fedora installation instructions


Gnuradio package from distribution Gnuradio 3.2.2 is in the Fedora default repository since Fedora 14 (Laughlin). Use yum or your favorite package installed to install it: yum install gnuradio usrp Gnuradio from tarball Install Fedora (FYI, we're known to work fine w/ Fedora 8, 9, 10, 11, 12 and 13), and then: $ yum groupinstall "Engineering and Scientific" "Development Tools" $ yum install fftw-devel cppunit-devel wxPython-devel libusb-devel \ guile boost-devel alsa-lib-devel numpy gsl-devel python-devel pygsl \ python-cheetah python-lxml guile-devel [[PyOpenGL]] $ yum install PyQt4-devel qwt-devel qwtplot3d-qt4-devel (The pkg names depend on the version of Fedora. These work for 12) You now have the basic requirements for building GNU Radio. Additional requirements are listed below. Notice that some are optional. Once you have all the requirements installed, you can proceed with the source code download and installation instructions.

USRP To build the firmware for the microcontroller on the USRP, you also need the Small Device C Compiler: http://sdcc.sourceforge.net/ . On Fedora Core 6 and later sdcc is available from the repository, and can therefore be installed by running: $ yum install sdcc Some of the names of the binaries in sdcc are very generic, and they have therefore been moved to /usr/libexec/sdcc on Fedora(http://www.fedoraproject.org ), and symlinks prefixed with sdcchave been created in /usr/bin. This might be a problem for existing programs, but the solution is simply to add /usr/libexec/sdcc to your PATH before building GNU Radio: $ export PATH=/usr/libexec/sdcc:$PATH The version of sdcc packaged for Fedora 11 (2.9.0) does not work with GNU Radio 3.2. It is possible to use the version packaged for Fedora 10 (2.8.0) available for i386:

(http://download.fedoraproject.org/pub/fedora/linux/releases/10/Everything/i386/os/sdcc-2.8.02.fc10.i386.rpm ) and x86_64: (http://download.fedoraproject.org/pub/fedora/linux/releases/10/Everything/x86_64/os/sdcc2.8.0-2.fc10.x86_64.rpm ). Alternatively sdcc 2.9.0 can be compiled from source available here. http://sdcc.sourceforge.net/ On earlier versions of Fedora you have to download the Small Device C Compiler, build and install yourself.get it here http://sdcc.sourceforge.net/

Documentation If you wish to be able to generate the HTML documentation: $ yum install xmlto graphviz

Qt GUI If you want to build the gr-qtgui package to use Qt plotting tools, install: $ yum install qt4-devel qwt-devel qwtplot3d-qt4-devel PyQt4-devel PyQwt-devel

Post installation instructions UDEV Follow these directions (http://gnuradio.org/redmine/projects/gnuradio/wiki/UdevConfig )to configure non-root access to the USRP.

Python The default install path for GNU Radio is /usr/local, but this is not part of the default Python module search path. The easiest way to that is to add this to ~/.bashrc or in the personal initialization file for your favourite shell. Determine what version of python you are using:

$ python -V Python 2.5 Then set the PYTHONPATH environment variable to a value that includes your installation prefix and the appropriate python version. E.g., x86 (32-bit) systems: export PYTHONPATH=/usr/local/lib/python2.5/site-packages X86-64 systems: export PYTHONPATH=/usr/local/lib64/python2.5/site-packages You can also run this from the command line before running GNU Radio applications.

Gentoo Linux installation instructions


Firstly emerge the packages that gnuradio depends on. $ emerge swig fftw cppunit boost alsa-lib sdcc guile wxpython xmlto numpy gsl Configuring using autotools Next download a release tarball or the source from github and perform the standard build and install procedure. Add "--prefix=/usr/" to the ./configure command to install the components to the correct location for Gentoo. $ ./bootstrap $ ./configure --prefix=/usr/ $ make $ make check $ make install

Configuring using cmake After version 2.4.2 there is the possibility of building using cmake, in order to do this follow these build instructions from the git directory: mkdir build cd build cmake-gui ../ At this point a gui should pop up, press configure in order to see what parameters can be altered. In order to change the correct location change the prefix from /usr/local to /usr. The qwt library is not found, change this to /usr/include/qwt5 and press configure again. The changes should now appear in red. Make sure the GR_QTGUI is now checked (it should be in red) and press generate.If you do not have the gui installed the following should suffice: cmake -DCMAKE_INSTALL_PREFIX=/usr -DQWT_INCLUDE_DIRS=/usr/include/qwt5 ../ However, this will not give you the overview that the gui does.When the generation is done, do: make make test su [Enter root password] make install After these simple steps you should have a working GNU Radio install on your Gentoo system. If anything goes wrong, please make sure you have a clean git repository to work from. From the git directory do: git clean -dfx and try the installation procedure again.

Mandriva installation
This information worked fine for Mandriva 2007.1 You should NOT need to compile any dependencies from source. EVERYTHING is available as a package. The install should be trivial. Some packages you will need to install if not already installed:

autoconf, automake, libtool libpython-devel swig libcppunit-devel libboost1-devel sdcc (for --enable-usrp) wxPythonGTK (for --enable-gr-wxgui)

You can install these packages by using your favourite package manager. Then follow instructions at BuildGuide as mentioned before .

OpenSUSE installation
This information should work for openSUSE 11.1, and also hopefully SuSE 10.1. If you choose to use downloadable packages, get the most recent package version, then use rpm to install (rpm -ivh package_filename). To install dependencies using the YAST2 package manager, issue "sudo /sbin/yast2" and a GUI will be brought up. Search for each package to install, find the correct package name, then hit the spacebar to mark it for installation.

gnuradio-core: As of GNU Radio 3.2, in order for 'configure' to execute, you need the following YAST2 packages, if they are not already installed: o autoconf, automake, libtool, make o python-devel o swig o fftw3-devel o cppunit-devel o boost-devel o guile o gsl-devel In order to execute some parts of gnuradio-core (a runtime dependency), you will need to install NUMPY either from package or from source (http://numpy.scipy.org/). If from source, after extracting execute "sudo python setup.py install". GRC: Install the following using YAST2: o python-lxml o python-gtk o libxslt-python You will also need to install Cheetah from source (http://www.cheetahtemplate.org/). After extracting, execute "sudo python setup.py install". USRP and related components: o Install the following using yast2: libusb-devel (the 0.1 series, not the 1.0 series) o You will need also install SDCC either from package or source (http://sdcc.sourceforge.net/). If from source, then you also need to install using yast2: bison flex before doing the usual "./configure && make && sudo make install". SDL-video: Install the following using YAST2: o SDL-devel WXGUI: Install the following using YAST2: o python-wxGTK JACK audio: Install the following using YAST2: o libjack-devel PortAudio audio: Install the following using YAST2: o libportaudio-devel

ALSA audio: Install the following using YAST2: o alsa-devel QTGUI: Install the following using YAST2: o libqt4-devel You will also need to install from package or source QWT (http://qwt.sourceforce.net/) and QwtPlot3d (http://qwtplot3d.sourceforge.net/). For QWT for the usual Linux installation, you need to edit qwtconfig.pri and change the 'INSTALLBASE' to '/usr/local', and 'headers.path' to '$$INSTALLBASE/include/qwt'; then execute 'qmake && make && sudo make install'. For QwtPlot3d, ignore the error when unpacking the tarball; issue "qmake && make" to make. To install, use the following script from the qwtplot3d top-level directory:
o o o

sudo mkdir /usr/local/include/qwtplot3d (cd include; tar cf - . | (cd /usr/local/include/qwtplot3d; sudo tar xf -)) tar cf - lib | (cd /usr/local; sudo tar xf -)

Then follow instructions at BuildGuide as mentioned before .

Accessing the USRP as a non-root user SuSE 10.1 uses "udev" rather than "hotplug" to automatically handle plug/unplug events for usb devices. To allow users other than root to use the USRP, follow these directions:

Note:If you're using UHD, you've probably done something like this already. This is really only necessary when using a USRP1 with the deprecated libusrp. The udev daemon is used by some Linux distributions to handle plug/unplug events for usb devices. Follow these steps to allow users other than root to use the USRP:

Setup udev for the usrp 1. Define a group for the usrp sudo groupadd usrp 2. Add users to the usrp group sudo usermod -a -G usrp [username] 3. Add a new udev rule
echo 'ACTION=="add", BUS=="usb", SYSFS{idVendor}=="fffe", SYSFS{idProduct}=="0002", GROUP:="usrp", MODE:="0660"' > tmpfile sudo chown root.root tmpfile sudo mv tmpfile /etc/udev/rules.d/10-usrp.rules

4. Load the new udev rule sudo udevadm control --reload-rules

Verify the setup Power cycle the usrp device and: lsusb | grep fffe:0002 You should see an entry with ID: fffe:0002 ls -lR /dev/bus/usb You should see a device file with group usrp and mode crw-rw----

Building GNU Radio on Ubuntu Linux


Installation Overview Installing GNU Radio on any recent Ubuntu is easy and requires the following steps: 1. 2. 3. 4. Install the pre-requisites Get the GNU Radio source code Configure, compile and install GNU Radio Configure USRP (optional)

Instructions for each of these steps are given below. Install the Pre-Requisites The following packages are required for compiling various parts of GNU Radio on Ubuntu. These packages can be installed via "synaptic" or using the command lines .

Development Tools (need for compilation) o g++ o git o make o autoconf, automake, libtool o sdcc (from "universe") o guile o ccache (not required, but recommended if you compile frequently) Libraries (need for runtime and for compilation) o python-dev o SWIG o FFTW 3.X (libfftw3-dev) o cppunit (libcppunit-dev) o Boost 1.35 (or later) o GSL GNU Scientific Library (libgsl0-dev) o libusb and libusb-dev o ALSA (alsa-base, libasound2 and libasound2-dev) GNU Radio Companion o for the GNU Radio Companion (GRC) you need to install python-numpy, pythoncheetah and python-lxml WX GUI

for the WX GUI components you need to install python-wxgtk2.8 and pythonnumpy

QT GUI o for the QT GUI components you need to install PyQT4, PyQwt5 for Qt4, QTOpenGL, Fontconfig, Xrender and Xinput (python-qt4, python-qwt5-qt4, libqt4opengl-dev, libqwt5-qt4-dev, libfontconfig1-dev, libxrender-dev, libxi-dev) Video-SDL o for Video-SDL you need to install the Simple DirectMedia Layer development libraries (libsdl1.2-dev) Polyphase Filter Bank examples o for the examples in gnuradio-examples/python/pfb to work you need to install python-scipy, python-matplotlib, and python-tk Other useful packages o doxygen (for creating documentation from source code) o octave (from "universe")

Install Dependencies The following command line scripts will install all the required dependencies. Before running them you should ensure that the Universe repository are enabled in "Software Sources". To execute the script copy & paste the relevant command line into a terminal. Natty Narwhal (11.04) sudo apt-get -y install git-core autoconf automake libtool g++ python-dev swig \ pkg-config libboost-all-dev libfftw3-dev libcppunit-dev libgsl0-dev \ libusb-dev sdcc libsdl1.2-dev python-wxgtk2.8 python-numpy \ python-cheetah python-lxml doxygen python-qt4 python-qwt5-qt4 libxi-dev \ libqt4-opengl-dev libqwt5-qt4-dev libfontconfig1-dev libxrender-dev Maverick (10.10) sudo apt-get -y install libfontconfig1-dev libxrender-dev libpulse-dev \ swig g++ automake autoconf libtool python-dev libfftw3-dev \ libcppunit-dev libboost-all-dev libusb-dev fort77 sdcc sdcc-libraries \ libsdl1.2-dev python-wxgtk2.8 git guile-1.8-dev \ libqt4-dev python-numpy ccache python-opengl libgsl0-dev \ python-cheetah python-lxml doxygen qt4-dev-tools \ libqwt5-qt4-dev libqwtplot3d-qt4-dev pyqt4-dev-tools python-qwt5-qt4

Lucid (10.04) sudo apt-get -y install libfontconfig1-dev libxrender-dev libpulse-dev \ swig g++ automake autoconf libtool python-dev libfftw3-dev \ libcppunit-dev libboost-all-dev libusb-dev fort77 sdcc sdcc-libraries \ libsdl1.2-dev python-wxgtk2.8 git-core guile-1.8-dev \ libqt4-dev python-numpy ccache python-opengl libgsl0-dev \ python-cheetah python-lxml doxygen qt4-dev-tools \ libqwt5-qt4-dev libqwtplot3d-qt4-dev pyqt4-dev-tools python-qwt5-qt4

Installing GNU Radio Download GNU Radio from the git master tree: git clone http://gnuradio.org/git/gnuradio.git or git clone git://gnuradio.org/gnuradio.git Bootstrap, configure and build GNU Radio cd gnuradio ./bootstrap ./configure Make Notes:

If you want to use GNU Radio with a USRP, see UHD instructions If you are building from a release .tar.gz rather than git you should skip the bootstrap step. By default GNU Radio will be installed under /usr/local After successful build you should run the GNU Radio software self-check (does not require USRP):

make check If any test or tests do not work, GNU Radio might still function properly, but it might be wise to look in the email archives for a fix or to write the email list. If writing to the email list, please include the OS type, OS version, and CPU type (e.g. via "uname -a"), anything special about the computer hardware, software versions (gcc, g++, swig, sdcc, etc) and how installed (standard or non-standard package, source). You can find some useful tips for asking questions under Reporting Errors.

Now install GNU Radio for general use: sudo make install You are now ready to use GNU Radio. You can try to execute the dial_tone.py example (/usr/local/share/gnuradio/examples/audio/dial_tone.py) or the gnuradio-companion.

Configuring USRP support This section is only relevant if you have a USRP1 that you want to use with GNU Radio. You may already have done this if you have installed UHD . Ubuntu uses udev for handling hotplug devices, and does not by default provide non-root access to the USRP. The following script is taken from directions, and sets up groups to handle USRP via USB, either live or hot-plug sudo addgroup usrp sudo usermod -G usrp -a <YOUR_USERNAME> echo 'ACTION=="add", BUS=="usb", SYSFS{idVendor}=="fffe", SYSFS{idProduct}=="0002", GROUP:="usrp", MODE:="0660"' > tmpfile sudo chown root.root tmpfile sudo mv tmpfile /etc/udev/rules.d/10-usrp.rules At this point, Ubuntu is configured to know what to do if/when it detects the USRP on the USB, except that "udev" needs to reload the rules to include the newly created one. The following might work, but if it doesn't then rebooting the computer will. sudo udevadm control --reload-rules or sudo /etc/init.d/udev stop sudo /etc/init.d/udev start or sudo killall -HUP udevd You can check if the USRP is being recognized, by examining /dev/bus/usb after plugging in a USRP. Using the command: ls -lR /dev/bus/usb | grep usrp should result in one or more lines (one for each USRP) reading something like:

crw-rw---- 1 root usrp 189, 514 Mar 24 09:46 003 Each device file will be listed with group 'usrp' and mode 'crw-rw----'. Once you've verified that the USRP is available to Ubuntu, now it is time to verify that GNU Radio works with the USRP. While "usrp_benchmark_usb" might not return a full 32 MB/s of throughput, the script should at least run properly; if not, either GNU Radio didn't make correctly or the USRP isn't accessible. From the "gnuradio" directory, verify that all of the following work:

Python interface to the USRP; provides a rough estimate of the maximum throughput (quantized to a power of 2) between the host computer and the USRP.

cd gnuradio-examples/python/usrp ./usrp_benchmark_usb.py

C++ interface to the USRP; provides a good estimate of the maximum throughput (nonquantized) between the host computer and the USRP.

cd usrp/host/apps ./test_usrp_standard_tx ./test_usrp_standard_rx You are now ready to use GNU Radio and your USRP.

Installing in a custom directory The generic instructions above install GNU Radio to /usr/local. It is however possible to install to a location of your choice. In order to do that you have to configure the build to use the custom prefix: ./boostrap ./configure --prefix=/opt/gnuradio ... This will configure GNU Radio to be installed to /opt/gnuradio rather than the default /usr/local It is now necessary to add the custom installation directories to our environment settings, otherwise applications will not be able to find the headers, libraries, python scripts, etc. Open your .bashrc file (e.g. type "gedit .bashrc" in the terminal) and add to the end of the file:

# GNU Radio installation export PATH=$PATH:/opt/gnuradio/bin export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/gnuradio/lib export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/opt/gnuradio/lib/pkgconfig export PYTHONPATH=$PYTHONPATH:/opt/gnuradio/lib/python2.6/site-packages The changes will take effect when you restart your session, e.g. log out and log in again.

Broken libtool on Debian and Ubuntu Note: This section seems obsolete for recent Ubuntu and you should consider it only if you encounter the problems mentioned below. Because Debian and Ubuntu apply a poorly implemented "enhancement" to the upstream version of libtool, they break the ability to test code and libraries prior to installing them. We think that testing before installation is a good idea. To work around their damage, be sure to include $PREFIX/lib (and $PREFIX/lib64 on 64-bit machines) in /etc/ld.so.conf. If you don't include $PREFIX/lib in /etc/ld.so.conf, you will see errors during the linking phase of the build. There are several places it shows up. The first one is often during the build of mblocks. It's not an mblock problem. It's a Debian/Ubuntu problem. Do this to work around this "feature": 1) Make a copy from the current ld.so.conf file and save it in a temp folder: cp /etc/ld.so.conf /tmp/ld.so.conf 2) Add /usr/local/lib path to it: echo /usr/local/lib >> /tmp/ld.so.conf 3) Delete the original ld.so.conf file and put the modified file instead: sudo mv /tmp/ld.so.conf /etc/ld.so.conf 4) Do ldconfig: sudo ldconfig

Installation on the Play Station 3


Fedora 8 can be installed on the PS3. It has improved kernels, libraries, compilers, and more. It is compatible with the Cell SDK 3.0 and it is easy enough to install on the PS3. IT MUST BE INSTALLED IN TEXT MODE AS FOLLOWS: You'll want to have a USB/RF keyboard attached to the PS3 at this point.

Installation Instructions

Get installation materials; need 1 blank DVD, 1 blank CD.

Download Fedora 8 DVD image (ISO) Torrent Image (recommended): "(Fedora-8-ppc):mirrors: http://mirrors.fedoraproject.org/publiclist/Fedora/8/ppc/ Download the latest Cell ADDON CD iso : [http://www.kernel.org/pub/linux/kernel/people/geoff/cell/ps3-distrokit/":http://torrent.fedoraproject.org/torrents/Fedora-8-dvd-ppc.torrent]

Burn the ISO's to disc (do this for both files downloaded above) o In Linux: cdrecord --device=<cdwriter-device> -tao -eject <image-file.iso> o Or use whatever DVD/CD burning tool you prefer (k3b is nice under KDE) Update the firmware on your PS3 to the latest (2.41 as of the time this was written). Format your PS3's harddrive (this will erase all data on the entire drive) o There are four options for a 60 GB harddrive: 1. All to PS3 2. All to Other OS 3. 10 GB to Other OS and rest to PS3 4. 10 GB to PS3 and rest to Other OS o choose either option 2 or 4. o In the XMB menum, go to Settings --> System Settings --> Format Utility Be sure to select Quick format (10 seconds) or you'll be waiting 3.5 hours. Install the Linux boot loader o Insert the ADDON iso CD that you made into the PS3 o In XMB navigate to Settings --> System Settings --> Install Other OS

The console should automatically detect the necessary files on the CD Follow the prompts to install the bootloader onto the hard drive

Change default OS to Other OS o Insert the FC-8-ppc DVD into the PS3. Then, o Settings --> System Settings --> Default System: change from PS3 to Other OS o If everything is working, you'll see a kboot prompt. At the kboot command prompt, enter: linux64 xdriver=fbdev video=720p install text o If video resolution 720p does not work please consult o "* Note that there are different options depending on where in the world you are located. Answer anaconda's questions o When you get to the part about what packages to install, select only Software Development and Customize Later o Unlike FC 7, you can install the default partitions. They work perfectly. Wait... a while. The PS3 looks frozen for a bit, then it will start installing files. This process takes 4 - 5 hours. It will eventually eject the DVD, say that it's rebooting, and hang ;) o Press and hold the power button until it beeps the second time (about 7 seconds), then release o Press it again. It'll boot the new system. Answer the first boot questions: set root passwd, create regular user, etc... o It will hang again on reboot, so hold power button again After reboot do a yum update and the next kernel you get will reboot! After the hours of updates are done go to [http://www.kernel.org/pub/linux/kernel/people/geoff/cell/ps3utils/":http://manuals.playstation.net/document/en/ps3/current/settings/videooutput.html]. (PS3-Utils) o Download all rpms and install them with rpm -ivh o Download the latest tbz of the ps3-utils (currently ps3-utils-2.2.0.tar.bz2) o tar jxf the tbz in a convenient place. Make sure the rpms are installed. o ./configure && make o sudo make install o This will give you the flash, OS swap, video mode utilities Reboot and ENJOY! You may now install SDK 3.0. o run sudo yum install compat-expat1

Beware. You will likely need to block the fedora repositories in /etc/yum.repos.d by changing all o enable=1 to enable=0 AFTER you have installed compat-expat1 to get the right libraries and utilities o for the Cell processor. Make sure that after the SDK is installed you enable the fedora and fedora-updates o repositories again.
o

In /etc/yum.conf place the line o exclude=blas blas-devel oprofile-debuginfo oprofile numactl numactl-devel o you may need to yum erase these files before you install the SDK o sudo yum erase blas blas-devel oprofile-debuginfo oprofile numactl numactldevel o will do the trick. More detailed instructions for the SDK are below, almost a o complete walk through. Develop PS3 apps!

Installation of GNU Radio on F8 on the PS3 Disable any rawhide repositories in the files /etc/yum.repo.d as they are inconsistent with the use of SDK 3.0

Install prerequisites

$ sudo yum groupinstall "Development Tools" $ sudo yum install fftw-devel cppunit-devel libusb-devel guile boost-devel alsa-lib-devel pythondevel numpy swig sdcc gsl-devel pygsl

SDCC is installed in a slightly strange way here, so fix some of the links:

Some of the names of the binaries in sdcc are very generic, and they have therefore been moved to /usr/libexec/sdcc on Fedora(http://www.fedoraproject.org/ ), and symlinks prefixed with sdcchave been created in /usr/bin. This might be a problem for existing programs, but the solution is simply to add /usr/libexec/sdcc to your PATH before building GNU Radio: $ export PATH=/usr/libexec/sdcc:$PATH

Get the GNU Radio installation from Subversion and install it

svn co http://gnuradio.org/svn/gnuradio/trunk cd trunk ./bootstrap ./configure make sudo make install

Set PYTHONPATH to point to the default /usr/local installation directory: o export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.5/sitepackages/ o Set this in your login script ~/.bashrc to automatically load on login Add USRP udev rule: o Follow instructions to allow non-root users to access the USRP.( explained in openSUSE installatiojn section . )

Using GNU Radio


Installing the IBM Cell SDK version 3.0 continued To successfully install all the correct tools on Fedora 8 the following additions to the SDK installation instructions are needed: sudo yum install compat-expat1 yum-fastestmirror yum-skip-broken sudo yum erase oprofile oprofile-debuginfo blas blas-devel numactl numactl-devel sudo vi /etc/yum.repos.d/fedora.repo and change the enable=1 to enable=0 sudo vi /etc/yum.repos.d/fedora-updates.repo and change the enable=1 to enable=0 Follow the download and installation instructions here : http://www.ibm.com/developerworks/power/index.html You'll need to create an IBM ID if you don't already have one. Following the successful COMPLETION of the installation (sudo /opt/cell/cellsdk verify gives all the right answers) do the following: sudo vi /etc/yum.conf

and add a line exclude=blas blas-devel oprofile oprofile-debuginfo numactl numactl-devel sudo vi /etc/yum.repos.d/fedora.repo and change the enable=0 you did above back to enable=1 sudo vi /etc/yum.repos.d/fedora-updates.repo and change the enable=0 you did above back to enable=1 run sudo yum update just to make sure it is now checking all of the following repositories fedora, fedora-updates, cellsdk-open, cellsdk-fedora, and cellsdk-extras-fedora. make sure that the ppu32-gcc compiler is in your PATH, otherwise: export PATH=/opt/cell/toolchain/bin:$PATH Note, the IBM SDK contains both free and non-free software. We're only using the free stuff, and it should be possible to get the free stuff without agreeing to IBM's non-free licenses. Perhaps somebody with some time can sort this out. Hint: They install in /etc/yum.repos.d/cellsdk-Fedora.repo I think all the free stuff is in the CellSDK-Open-Fedora-* repository at the Barcelona Supercomputing Center.

Cross Compiling for the Cell Now that you've got all the software installed and have discovered that compiling on the PS3 (or QS21 for that matter) takes nearly forever, please check out these instructions for CrossCompilingForCell. It's how most of us do our actual Cell development.

USRP FPGA Firmware


To compile the verilog source code for the fpga firmware for the usrp you need Altera Quartus II Web Edition. This is only needed if you change the verilog code, since the distribution contains pre-compiled versions of this firmware.

Running Altera Quartus II Web Edition under Linux To generate the firmware for the altera Cyclone FPGA on the usrp from the usrp verilog sourcecode you need Quartus II Web Edition version 5.1 or later. Unfortunately this is not opensource, but there is a free download with from the altera website. You also need to get a free license. Download Quartus II Web edition: https://www.altera.com/support/software/download/sofdownload_center.html This is windows-only software. At the time of this writing, version 5.1SP1 and version 6.0 seems to work fine for the usrp verilog code. I don't think the 5.1SP1 version is still available for download (the 6.0SPx version is) The files I downloaded and tested were: quartusii_51_sp1_web_edition.exe quartusii_60_sp1_web_edition.exe There are several ways to run this software under linux.

Method 1 Quartus using Wine: Install Wine version 0.9.19 or later (a recent cvs version will probably also work). (Older versions do not work, believe me, I tried. I even tried cxoffice.) Now make sure you set the emulated operating system to windows 98. (run winecfg and set Applicatios\default settings Windows to windows98) If you emulate windows 2000 it will not work. The problem is mainly that the licensing copy protection crashes. I have allways found it strange that you need to install a very invasive kernel_mode licensing/copyprotection tool to install software which is free to download with a license that is free and forever renewable.

If you want to get rid of any old wine settings and applications you can just move ~/.wine to something else and run winecfg. It will generate a clean .wine folder including default registry settings for you. Now run the quartus installer. make sure you select at least the quartus core component and the cyclone device, the tutorials are also probably handy. All other devices are not needed for the usrp. You don't really need the extra options you get when you select the talkback feature, so you can disable it. If you want to do timing analysis and stuff you should keep it selected. Quartus Ii 5.1SP1 should run to completion without any trouble. It might hang on the last screen. If you nothing happens for a very long time you can savely kill it with CRTL-C in the console which started wine. Now you need to get and install the (free) license. You can request it on the altera website. To request a license you need your NIC ID.

NIC ID The NIC ID is a 12-character hexadecimal string embedded in the network interface card that Altera uses to uniquely identify the PC where the software is installed. Wine should present your real NIC ID without alteration towine which will pas it to quartus. (beware, this is not the case for all emulators) There are multiple ways of getting this ID. Linux: Type /sbin/ifconfig eth0 at a command prompt. nldudok1@quarkdeb:/$ /sbin/ifconfig eth0 eth0 Link encap:Ethernet HWaddr 00:B0:D0:AB:CC:BA inet addr:192.168.0.1 Bcast:10.0.0.255 Mask:255.255.255.0 inet6 addr: fe80::213:ffff:aabb:ccdd/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:16137 errors:0 dropped:0 overruns:0 frame:0 TX packets:10640 errors:0 dropped:0 overruns:0 carrier:0 collisions:2 txqueuelen:1000 RX bytes:20428079 (19.4 MiB) TX bytes:898048 (877.0 KiB) Interrupt:58 Base address:0xe400 NIC ID is the ID to the right of HWaddr, without the colons, e.g., 00B0D0ABCCBA. To be sure wine sees exactly the same ID you can also use lmutil.exe which installed with quartus Do the following.

/$ cd ~/.wine/drive_c/altera/quartusXXX/win/ ~/.wine/drive_c/altera/quartusXXX/win$ wine lmutil.exe hostid Invoking /usr/lib/wine/wine.bin lmutil.exe hostid ... lmutil - Copyright (c) 1989-2003 by Macrovision Corporation. All rights reserved. The FLEXlm host ID of this machine is ""00b0d0abccba 001122334455"" Only use ONE from the list of hostids. Wine exited with a successful status In this case only use the first number (00b0d0abccba in the example above) Now you have the right NIC ID you can request a license on the altera website: Go back to the quatus download page and click "Get Web Edition License" . Download Quartus and get web edition license: https://www.altera.com/support/software/download/sof-download_center.html Fill out the form, including the NIC ID and a valid emailadres.You should now get a licensefile by email. Save the license file somewhere on you wine C-drive for example: ~/.wine/drive_c/altera/ For any other licensing problems see the altera licensing document Altera Software Licensing: http://www.altera.com/literature/an/an340.pdf Now it is time to start quartus. /$ cd ~/.wine/drive_c/altera/quartusXXX/bin/ ~/.wine/drive_c/altera/quartusXXX/bin$ wine quartus.exe Quartus 6.0 will open with a few errors: error:This program is for windows NT only. Click on OK. error:Quartus II is not fully registered, with a list of problems. Click on OK. Quartus 5.1SP will not have these errormessage. message: Quartus II help will only work if you have installed Internet Explorer 4.0 or higher. I haven't worked on this error yet. It might go away if you install the wine gecko fake IE or find a way to install a real IE. Quartus should now start with a license options screen. Choose, "I have a valid license" And direct it to C:\altera\ (or wherever you put the file) and choose the license file. You can allways change the license file and options with the Tools menu\License setup. Here you will also see the NICID you entered earlier.

Now you are ready to compile the usrp verilog code to a usrp????.rbf file. The easiest way is to open the usrp quartus project file gnuradiosrcdir/usrp/fpga/toplevel/usrp_std/usrp_std.qpf (Note with the default wine configuration you Z: drive is the same as /) If you want you can now try to set back the default settings of wine to windows 2000 and only run quartus.exe and quartus_sh.exe as windows 98. I have not tried this though. For this you have to run winecfg again.

Method 2 Quartus using qemu Warning :Untested Install a recent Qemu. Make a new virtual machine and install windows 98 or windows 2000 or windows XP. Download Quartus II (see above) Install Quartus within the virtual machine. Request a license file using the NICID of you virtual machine In you virtual windows do: Type ipconfig /all at a commandprompt. The NIC ID is the physical address without the dashes. If your PC has more than one network card, you can use any of the cards NIC IDs as long as the selected network card is always connected to the computer. Now you have the right NIC ID you can request a license on the altera website: Go back to the quatus download page and click "Get Web Edition License" . Download Quartus and get web edition license: https://www.altera.com/support/software/download/sof-download_center.html Fill out the form, including the NIC ID and a valid emailadres. You should now get a licensefile by email. Save the license file somewhere on you qemu virtual C-drive. Run quartus II from the start menu and choose "have valid license" You could also choose request a license now. (This should work within Qemu if you have networking setup and working)

Method 3: Quartus using VMware Install some flavour of VMware. Make a new virtual machine and install windows 2000 or windows XP. Download Quartus II (see above) Install Quartus within the virtual machine.

Request a license file using the NICID of you virtual machine In you virtual windows do: Type ipconfig /all at a commandprompt. The NIC ID is the physical address without the dashes. If your PC has more than one network card, you can use any of the cards NIC IDs as long as the selected network card is always connected to the computer. Now you have the right NIC ID you can request a license on the altera website: Go back to the quatus download page and click "Get Web Edition License" . Download Quartus and get web edition license: https://www.altera.com/support/software/download/sof-download_center.html Fill out the form, including the NIC ID and a valid emailadres.You should now get a licensefile by email. Save the license file somewhere on you vmware virtual C-drive. Run quartus II from the start menu and choose "have valid license" You could also choose "request a license now". (This should work within VMware if you have networking setup and working)

I have used the VMware method for a long time now. It works, is stable and the speed is usable. But I don't like having to install a complete windows inside my linux machine just to run one program. The same disadvantage goes for Qemu. (although Qemu itself is a very nice opensource product which I can recommend to anyone.) The wine method doesn't need any microsoft components. It is less stable though and only works if you emulate windows 98, which is not supported anymore by quartus II 6.0 and later. I had a few crashes already, but also succesfull compiles (both with version 5.1SP1 and 6.0SP1) I hope this is of help to others trying to develop opensource verilog code but who are forced to running closed-source windows programs. Current Known Build Problems: http://gnuradio.org/redmine/projects/gnuradio/issues?query_id=1

GNU Radio on Mac OS X


Overview GNU Radio is distributed as source code. Therefore, the installation procedure is rather elaborate: you must also install the tools and libraries needed to build GNU Radio, not just to run it. But once you have done that, you are all set up to be a GNU Radio developer, not just a user.

Prerequisites We installed Apple's Xcode programming tools and libraries, but we don't use the Xcode GUI to build or install GNU Radio. We do it all from the command line (in a terminal window). We installed the Subversion (svn) version control system to check out the source code. GNU Radio no longer uses CVS. We installed MacPorts, a utility for installing and managing open-source software for the Mac. We installed the tools collectively called the autotools: autoconf, automake, libtool, and pkgconfig. We installed the swig tool. We installed the libraries boost, fftw-3-single, cppunit, and libusb. We installed the SDCC compiler. We got all of these from MacPorts. Details follow. We installed the wxPython GUI tools and libraries, the NumPy mathematics libraries. We didn't get these from MacPorts. Details follow.

Modules GNU Radio itself comes organized into several modules (separate collections of files). You choose which modules you want to install (although some modules depend on others). You identify the modules to install in the build configuration. We install gnuradio-core, gr-wxgui, usrp, gr-usrp, gr-audio-osx, gnuradio-examples, gr-utils, grhow-to-write-a-block, and omnithread. The gnuradio-core module is a self-contained system with no GUI and no device support. With just this module, you can code and test signal processing networks that get input and output from arrays, files, or sockets. The gr-wxgui module adds a GUI, including an oscilloscope and a spectrum analyzer. The usrp and gr-usrp modules add support for the USRP hardware, which is connected to the computer's USB port, and provides analog input and output at radio frequencies via programmable mixers (up- and down-converters).

The gr-audio-osx modules adds audio input and output using the Mac's built-in sound hardware. The gnuradio-examples module provides some sample programs that use the other modules. any programs that demonstrate the USRP are in this module. The gr-utils module provides more sample programs, emphasizing diagnostics.

Dependencies Here are the dependencies between some modules and prerequisites (where a: b c means a depends on b and c). gnuradio-core: gr-wxgui: usrp: gr-usrp: boost fftw-3-single cppunit NumPy gnuradio-core NumPy wxPython libusb sdcc usrp gnuradio-core

gnuradio-examples: usrp gnuradio-core gr-wxgui In addition to the dependencies shown here, the autotools are needed to build every module. The swig tool is needed to build every module except usrp.

Locations It is most convenient when the OS X software, the GNU Radio prerequisites, and GNU Radio itself are in different locations (because they are updated on different schedules, etc.) The prerequisites install themselves in four different places: /opt/local/... /usr/local/bin Prerequisites from MacPorts wxPython programs (not used by GNU Radio)

/usr/local/wxPython-ansi-2.6.1.0/... wxPython headers and libraries /Library/Python/2.3/... wxPython and NumPy Python libraries

You can choose where to build and install GNU Radio itself. We use: /Users/user/gnuradio/... GNU Radio build directory tree

/Users/user/gnuradio/gnuradio-core/... gnuradio-core module build directory /Users/user/gnuradio/gr-wxgui/... ... other modules ... /Users/user/gr/... gr-wxgui module build directory ... other module build directories ... GNU Radio installed files for all modules

Where user is the name of your home directory. For example, my installed GNU Radio files are under /Users/jon/gr/.... Checking out the GNU Radio sources from the Subversion repository creates the gnuradio build directory. You may put it wherever you want. It contains the module directories gnuradio/gnuradio-core etc. Details to come. The configure command you issue when you build GNU Radio puts the installed files under any directory you choose. Making a separate GNU Radio install directory gr is more convenient than installing the GNU Radio files among all the other software under /usr/local or /opt/local. For example, it makes it easy to experiment with multiple installed versions of GNU Radio. I put both gnuradio and gr under my home directory so I wouldn't have to fuss with permissions, admin accounts, or sudo to build or install. Environment variables We define several environment variables to build and run GNU Radio. Details to come. Installing the Prerequisites To install GNU Radio on recent Mac hardware and operating systems, consult the Build Guide and Mac Install pages at the GNU Radio Wiki: http://vps.gnuradio.org/redmine/wiki/gnuradio/BuildGuide, MacInstall: http://vps.gnuradio.org/redmine/wiki/gnuradio/MacInstall These pages describe our installation of GNU Radio 3.0 and 3.1 with the USRP hardware on Mac OS X 10.4 Tiger on PPC Macs.

Rationale The prerequisites are tools and libraries needed to install or use GNU Radio. They can be useful for other purposes also. Obtaining and installing the prerequisites is more work than installing GNU Radio itself. However, it rarely needs to be repeated. To build and use recent versions of GNU Radio, we still use many of the prerequisites we installed in 2005. Many prerequisites are available in several formats. Here are the alternatives, ranked from easiest to most difficult to install. 1. 2. 3. 4. Already included in OS X or provided by Apple MacPorts port Binary distribution for OS X (usually a .dmg file) source distribution (usually a .tar file)

We usually choose the easiest format, but sometimes the version required by GNU Radio is only available in a more difficult format. Install the prerequisites from an admin account. If a command fails because of permission or privilege problems, try again with sudo command. Python We don't install Python, we use the version that already comes with OS X. Currently we are running OS X version 10.4.10, which provides Python 2.3.5. At this writing the latest Python version is 2.5, but 2.3.5 is sufficient to build and run the latest GNU Radio. It is possible to install a newer version of Python on OS X in addition to the one that is provided, but this can create difficulties, so we have chosen not to. Sticking with Python 2.3.5 can be a bit inconvenient because some versions of other prerequisites depend on more recent Python versions. However, we have always been able to find a version of every prerequisite that works with Python 2.3.5. Details follow. Xcode We installed Apple's Xcode programming tools and libraries. Xcode provides gcc 4.0 and make. The Xcode tools install in /usr/bin. We don't use the Xcode GUI to build or install GNU Radio. We do it all from the command line, in a terminal window. Xcode 2.0 comes on the Tiger install DVD, but it is not installed automatically along with Tiger. After you install Tiger, load the Tiger DVD. Open the Xcode Tools folder; in that folder open

XCodeTools.mpkg to start the Xcode Tools Installer, then follow its directions. After the installation completes, run update (Apple Menu -> Software Update ...) to get up to the latest version. Alternatively, you can download the latest version of Xcode from the following URL at Apple. It's free, but you must register for Apple Developer Connection. http://developer.apple.com/tools/download/ At this writing (March 2008), Xcode 2.5 is the latest version for OS X version 10.4 (Tiger). There is a 3.0 version, but it is only for 10.5 (Leopard). Download the Xcode DMG (disk image) file. Opening this file mounts the Xcode Tools disk. On that disk, open XCodeTools.mpkg to start the Xcode Tools Iinstaller, then follow its directions. When the installation is finished, you can eject the disk (ctrl-Click, select Eject from the menu, or drag the disk icon to the trash).

Subversion We installed the Subversion (svn) version control system to check out the GNU Radio source code and build scripts from the repository. GNU Radio no longer uses CVS. Here we found a .dmg file that you can install in the usual way. http://metissian.com/projects/macosx/subversion/ Here is the main Subversion web site. http://subversion.tigris.org/

MacPorts MacPorts is a collection of open-source software packaged for Mac OS X. Get a package from MacPorts if you can; this is usually more convenient and less error-prone than building it from source. Most of the prerequisites for GNU Radio are available from MacPorts. MacPorts also refers to the package management tools. They maintain a database of packages available on the Internet and a registry of packages installed on your machine. The MacPorts port command is analogous to the rpm, apt-get, or dpkg commands available on some Linux systems. Use it to find, install, and query about the MacPorts software packages. The port install package command downloads and installs package, and any other packages on which it depends.

The MacPorts software packages (including the MacPorts tools themselves) install under /opt/local. This directory does not exist when Mac OS X is installed. Installing the MacPorts tools creates it (if it has not already been created for some other reason). Install the MacPorts tools first. Go to the Get MacPorts page and follow the directions there. http://www.macports.org/install.php After the installation completes, run the command sudo port -d selfupdate To bring your installation up to date. When you use MacPorts, the directory /opt/local/bin must be in your PATH so your process can find the MacPorts tools. This directory must appear before /usr/bin in your PATH, so you will be sure to use the MacPorts version of a tool rather than any older version that might be provided by Xcode. You can ensure this by putting a line like this one in your .profile file.
export PATH=/opt/local/bin:/opt/local/sbin:/bin:/sbin:/usr/bin:/usr/sbin:~/bin:/usr/local/bin:... other directories ...

Here are some useful MacPorts commands. MacPorts calls a package a port; its name is its portname. man port port list port search regexp port installed port info portname port deps portname port install portname port contents portname List information about the port command. List all available ports (a great many!) List all available ports whose names match the regular expression List installed ports List information about portname (any available, not just installed) List dependencies, other ports required to build and run portname Download and install portname (and any ports on which it depends) List files installed by portname

port dependents portname List installed ports that depend on portname port provides filename Name the port that installed filename

port -d selfupdate port -a upgrade port -u uninstall

Update MacPorts tools and database Upgrade all outdated ports (after selfupdate) Uninstall all installed but inactive ports (after upgrade)

autotools The autotools are programs that automate building software packages on multiple platforms. They are needed to build GNU Radio. GNU Radio requires these tools and versions, according to the README in the top-level gnuradio build directory. autonconf 2.57 or later automake 1.7.4 or later libtool 1.5 or later pkgconfig 0.15.0 or later All of the autotools are available from MacPorts. To install the autotools, execute the following commands: $ sudo port install autoconf ... $ sudo port install automake ... $ sudo port install libtool ... $ sudo port install pkgconfig ... Confirm that you have succesfully installed the autotools: $ port installed The following ports are currently installed: autoconf 2.59_0 (active) automake 1.9.5_0 (active) libtool 1.5.20_0 (active) pkgconfig 0.19_0 (active) Confirm that your PATH is set correctly, so you execute the MacPorts versions and not any older Xcode versions.

$ which automake /opt/local/bin/automake $ automake --version automake (GNU automake) 1.9.5 ... Contrast this to the older version installed by Xcode, which will not build GNU Radio. $ /usr/bin/automake --version automake (GNU automake) 1.6.3

swig Swig is a tool that enables Python code to call C++ code. GNU Radio requires swig 1.3.23 or later. Swig is available from MacPorts. Install it and confirm the installation in the usual way. $ sudo port install swig ... $ port installed ... swig 1.3.25_0 (active)

Core libraries Several libraries are required to build gnuradio-core: Boost C++ libraries 1.31 recommended, presumably later is OK cppunit 1.9.14 or later FFTW3 3.0 or later These are all available from MacPorts. Boost and cppunit can be installed and confirmed as usual. $ sudo port install boost ... $ sudo port install cppunit ... $ port installed ... boost 1.32.0_0 (active) boost-jam 3.1.11_0 (active) cppunit 1.11.0_0 (active)

These installations can take many minutes so be patient and don't panic. You can view the output of top -o cpu in a different window to reassure yourself that the installation in proceeding. To get the right version of FFTW3, install the MacPorts fftw-3-single package (thanks to Michael Dickens for pointing this out). $ sudo port install fftw-3-single ... When the installation completes, make sure you have the libfftw3f libraries (with an f at the end of the name), not libfftw3. $ port contents fftw-3-single Port fftw-3-single contains: ... /opt/local/lib/libfftw3f.a /opt/local/lib/libfftw3f.la /opt/local/lib/libfftw3f_threads.a /opt/local/lib/libfftw3f_threads.la /opt/local/lib/pkgconfig/fftw3f.pc ...

NumPy and SciPy NumPy is a Python numeric library. It is required to run both gnuradio-core and gr-wxgui (it is not required to build them). GNU Radio no longer uses Numeric. NumPy has replaced Numeric. We also use SciPy, a scientific programming package that uses NumPy. SciPy is not required by GNU Radio itself, but it is required by our MRFM software. To install NumPy, SciPy, and their prerequisites we followed these directions: http://www.scipy.org/Installing_SciPy/Mac_OS_X except we declined their recommendation to install a newer Python. In summary: 1. Following the recommendation on compilers in the SciPy FAQ at http://www.scipy.org/FAQ#head-f94e8674db29e47e399dc7390f8c1e0f708ab7f2

we build everything with GCC 3.3: $ sudo gcc_select 3.3 $ gcc -dumpversion # check GCC version 3.3 2. Download the g77 Fortran binary g77-bin.tar.gz from the link on http://hpc.sourceforge.net/ And install it using the instructions on that same page. 3. Download the FFTW library source fftw-3.1.2.tar.gz from http://fftw.org/fftw-3.1.2.tar.gz And install using the instructions on Installing_SciPy/Mac_OS_X: http://www.scipy.org/Installing_SciPy/Mac_OS_X We already installed an FFTW library from MacPorts for GNU Radio, but SciPy needs this different version of FFTW, and looks for it in a different place. 4. Download the NumPy source numpy-1.0.1.tar.gz from the link on http://www.scipy.org/Download And install using the instructions on Installing_SciPy/Mac_OS_X: http://www.scipy.org/Installing_SciPy/Mac_OS_X 5. Download the SciPy source scipy-0.5.2.tar.gz from the link on http://www.scipy.org/Download And install using the instructions on Installing_SciPy/Mac_OS_X. Note the special instruction for g77. http://www.scipy.org/Installing_SciPy/Mac_OS_X We installed these in March 2007. More recent versions of some packages are now available.

wxPython wxPython provides the GUI for GNU Radio. It is a prerequisite for the gr-wxgui module only. You don't need wxPython to build and use gnuradio-core. wxPython is available as the MacPorts package py-wxpython, but this package requires python24, so we don't use it. The version we run uses the Mac's already installed Python 2.3. We are using version wxPython 2.6.1.0, which we installed in August 2005. At this writing, it still works with recent versions of GNU Radio (trunk, and 3.1 stable branch). We see the latest version is 2.8, which is available for Python 2.3 on OS X. Get the binary disk image for the Mac from the wxPython download page. http://www.wxpython.org/download.php#binaries From this page, find the section Mac OS X, wxPython Runtime, Panther (10.3.X). Follow the link osx-ansi. It leads to a SourceForge page with a lot of mirrors, pick one and download the disk image (.dmg) file. Open this file to mount the wxPython installation disk. On that disk, open the wxPython .pkg file to start the installer, then follow its directions. When the installation completes you will have many new executables and .py files in /usr/local/bin, a new directory and contents /usr/local/lib/wxPython-ansi-version, a new directory and contents /Library/Python/2.3/wx-version-mac-ansi and other new files in /Library/Python/2.3. You can also get documentation, demos, and samples from the wxPython downloads page by following osx-docs-demos, but these are not needed by GNU Radio. The version we are using, wxPython 2.6.1.0, was developed for Mac OS X 10.3 (Panther). To make it run under 10.4 (Tiger), we had to install another package from the wxPython site (you can also reach it by following links starting at the wxPython downloads page): http://pythonmac.org/packages/ Scroll down to TigerPython23Compat and download the .pkg.zip file. On download, it unzips and the installation begins. Follow the prompts. It installs the file _TigerPython2.3Compat.pth under /Library/Python/2.3/site-packages Check that installation succeeded by typing this command at the shell prompt: $ pyshell A python shell window should open up. (We don't use this command, we always run Python from a terminal window). Now we have all the prerequisites we need to install and use the gr-wxgui module.

libusb To use the USRP hardware, you must have libusb. It is a prerequisite for the usrp module. Get it from MacPorts. $ port info libusb libusb 0.1.10a, .... $ sudo port install libusb ... $ port installed ... libusb 0.1.10a_1 (active) ... $ port contents libusb Port libusb contains: ... /opt/local/bin/libusb-config /opt/local/include/usb.h /opt/local/include/usbpp.h ... /opt/local/lib/libusb.dylib ... /opt/local/lib/libusbpp.dylib ... We still need one more prerequisite for the usrp module.

SDCC SDCC is the small computer compiler collection. It is a prerequisite for the usrp module. Get it from MacPorts. SDCC might require some tweaking. The installation might fail, like this: $ port install sdcc ---> Fetching sdcc ---> Attempting to fetch sdcc-2.4.0.tar.gz from http://puzzle.dl.sourceforge.net/sdcc ---> Verifying checksum(s) for sdcc ---> Extracting sdcc ---> Configuring sdcc ---> Building sdcc with target all Error: Target com.apple.build returned: shell command "cd /opt/local/var/db/dports/build/file._opt_local_var_db_dports_sources_rsync.rsync.opendarwin.or g_dpupdate_dports_lang_sdcc/work/sdcc && gnumake all" returned error 2 ...

... many successful gcc commands ... gcc -Wall -pipe -ggdb -g -O2 -I. -I.. -I../support/Util -c SDCCutil.c -o SDCCutil.o In file included from SDCCutil.c:30: ../support/Util/dbuf.h:32: error: parse error before 'size_t' ../support/Util/dbuf.h:32: warning: no semicolon at end of struct or union ../support/Util/dbuf.h:33: warning: type defaults to 'int' in declaration of 'len' ../support/Util/dbuf.h:33: warning: data definition has no type or storage class ../support/Util/dbuf.h:35: error: parse error before '}' token ../support/Util/dbuf.h:42: error: parse error before 'size' ../support/Util/dbuf.h:43: error: parse error before 'size_t' ../support/Util/dbuf.h:44: error: parse error before 'size_t' ../support/Util/dbuf.h:45: error: parse error before 'size_t' ../support/Util/dbuf.h:47: error: parse error before 'dbuf_get_size' ../support/Util/dbuf.h:47: warning: type defaults to 'int' in declaration of 'dbuf_get_size' ../support/Util/dbuf.h:47: warning: data definition has no type or storage class SDCCutil.c: In function 'appendStrSet': SDCCutil.c:74: error: storage size of 'dbuf' isn't known SDCCutil.c:74: warning: unused variable 'dbuf' SDCCutil.c: In function 'joinStrSet': SDCCutil.c:97: error: storage size of 'dbuf' isn't known SDCCutil.c:97: warning: unused variable 'dbuf' gnumake[1]: *** [SDCCutil.o] Error 1 gnumake: *** [sdcc-cc] Error 2 To recover from this, go to the directory that contains SDCCutil.c, which is /opt/local/var/db/dports/build/_opt_local_var_db_dports_sources_rsync.rsync.darwinports.org_d pupdate_dports_lang_sdcc/work/sdcc/src/ Edit SDCCutil.c (with sudo). Search for dbuf.h, and move that whole line to the end of the #include's (4 lines below). Then, repeat the install command. It should resume at the step that failed, and complete successfully. (Thanks to Michael Dickens for this fix.) $ port install sdcc ---> Building sdcc with target all---> Staging sdcc into destroot ---> Packaging tgz archive for sdcc 2.4.0_0 ---> Installing sdcc 2.4.0_0 ---> Activating sdcc 2.4.0_0 ---> Cleaning sdcc $ port installed ... sdcc 2.4.0_0 (active) ... If the SDCC install still fails, you may have to assign these environment variables:

SDCC_LIB=/opt/local/share/sdcc/lib/ SDCC_INCLUDE=/opt/local/share/sdcc/include/ See thread starting at: http://lists.gnu.org/archive/html/discuss-gnuradio/2006-01/msg00167.html Now we have all the prerequisites we need for the USRP modules.

Installing GNU Radio on Mac


Overview Now that we have all the prerequisites we are ready to install GNU Radio itself. As explained in the Build Guide, the GNU Radio installation is a variant of the familiar procedure: configure, make, make install. A single pass through the procedure builds all the modules specified in the build configuration.

Environment variables We define some environment variables so we can build and run GNU Radio in our chosen locations. export GR=$HOME/gr export PYTHONPATH=$GR/lib/python2.3/site-packages export PKG_CONFIG_PATH=$GR/lib/pkgconfig:/opt/local/lib/pkgconfig export CPATH=$GR/include:/opt/local/include export LDFLAGS="-L$GR/lib -L/opt/local/lib" I put these commands in a gr-defs shell script in my ~/bin directory. Then I run that script in any shell (any terminal window) before I build or use GNU Radio. $ source gr-defs Using source gr-defs rather than just gr-defs ensures that the definitions persist in that shell after the script exits. To confirm that: $ printenv ... other variables GR=/Users/jon/gr PYTHONPATH=/Users/jon/gr/lib/python2.3/site-packages ... etc. Also, be sure your PATH includes /opt/local/bin. This is typically set in your .profile.

Subversion checkout To check out the GNU Radio sources from the Subversion repository, execute this command: $ svn co http://gnuradio.org/svn/gnuradio/branches/releases/3.1 gnuradio This checks out all modules for the 3.1 stable branch and puts them in a new directory gnuradio under the current directory. This is the GNU Radio build directory. I put mine under my home directory. Execute all the following commands in the gnuradio directory.

Bootstrap The libtool programs installed by MacPorts are named glibtool and glibtoolize. The build scripts in the GNU Radio distribution assume that they are named libtool and libtoolize. We fix this by making a copy of the bootstrap script bootstrap_mp where we change the line: libtoolize --automake to glibtoolize --automake (Thanks to Michael Dickens for this fix.) Execute it: $ ./bootstrap_mp

Configure We create a file configure-gr that invokes the configure command with our build configuration. Here the --prefix option sets the location of the installed software and the --disable and --enable options select the modules to install.

Our configure-gr has these contents: ./configure --prefix=$GR \ --disable-all-components \ --enable-gnuradio-core \ --enable-usrp \ --enable-gr-usrp \ --enable-gr-wxgui \ --enable-gr-audio-osx \ --enable-gnuradio-examples \ --enable-gr-utils \ --enable-gr-how-to-write-a-block \ --enable-omnithread For more about build configuration options, see the Wiki: http://gnuradio.org/redmine/wiki/gnuradio/BuildConfiguration Execute it: $ ./configure-gr When the configure command completes successfully, it writes this message: The following GNU Radio components have been successfully configured: config omnithread gnuradio-core pmt mblock usrp gr-usrp gr-audio-osx gr-wxgui gr-utils gnuradio-examples You may now run the make command to build these components.

Make Execute it: $ make On a 1 GHz Powerbook G4 this can take almost an hour.

Check The check command executes tests. $ make check Most tests pass. Messages similar to the following usually appear. They are expected and do not indicate a problem with the installation: Testing gr_vmcircbuf_createfilemapping_factory... gr_vmcircbuf_createfilemapping: createfilemapping is not available ....... gr_vmcircbuf_createfilemapping_factory: Doesn't work Testing gr_vmcircbuf_sysv_shm_factory... gr_vmcircbuf_sysv_shm: shmat (1): Too many open files gr_vmcircbuf_sysv_shm: shmget (1): Invalid argument ....... gr_vmcircbuf_sysv_shm_factory: Doesn't work Testing gr_vmcircbuf_mmap_shm_open_factory... ....... gr_vmcircbuf_mmap_shm_open_factory: OK Testing gr_vmcircbuf_mmap_tmpfile_factory... ....... gr_vmcircbuf_mmap_tmpfile_factory: OK

Install Execute it: $ make install Our installation directory is under our home directory, so there is no need to sudo. Now we have a new installed GNU Radio directory gr. Confirm that Python can find the GNU Radio installed files: $ python

... >>> from gnuradio import gr >>> If Python imports gr without complaint, GNU Radio is ready to use

Using the GUI Overview The gr-wxgui module adds a GUI to GNU Radio that you can use in your Python programs. There are also some standalone demonstration programs, including an oscilloscope and a spectrum analyzer. Building gr-wxgui The gr-wxgui module is built at the same time as the other GNU Radio modules, as directed in the build configuration. Using gr-wxgui To use gr-wxgui on the Mac you must run your Python program with the pythonw command (note the final 'w'), not python. The pythonw command calls an executable Python which is installed in a Mac app wrapper. The app contains an Info.plist file that enables Python to receive events from the Mac window manager. On slower Macs (1 GHz Powerbook G4 and below) the performance can be marginal. Sometimes the programs start up and display a blank window, or display some data and then freeze up, showing the twirling beachball icon that indicates the program is busy. Apparently wxPython can't always keep up with the data produced by the GNU Radio flow graph. Each GUI program provides different workarounds for this. The demos are in the build directory in gnuradio/gr-wxgui/python/src, and also in the installed directory in gr/lib/python2.3/site-packages/gnuradio/wxgui. To run the oscilloscope demo (screenshot): $ pythonw scopesink2.py 3 500 25e-6

The first argument 3 is frame_decim. Make this number larger if you see the spinning beachball, that samples the traces less frequently and loads wxPython less heavily. Here 3 is the smallest value that works on my 1 GHz Powerbook G4. The second argument 500 is v_scale, the vertical scale in counts/division. The third argument is t_scale, the time scale in seconds/division; 25e-6 is 25 microseconds/division. You can reduce the load on wxPython by choosing a smaller value for t_scale, so fewer cycles of data appear on the display. Omit an argument to accept the default: frame_decim 1, v_scale autorange, t_scale 100 microseconds/division. The default for frame_decim can be set in gr/etc/gnuradio/conf.d/gr-wxgui.conf. The preset default 1 does not work on my 1 GHz Powerbook G4. GNU Radio versions before 3.1 provide the older scopesink.py instead of scopesink2.py To run the spectrum analyzer demo (screenshot): $ pythonw fftsink2.py

Use ctrl-click to bring up a menu of controls. The load on wxPython is set by the fft_rate parameter in the code. The default for fft_rate can be set in gr/etc/gnuradio/conf.d/gr-wxgui.conf The preset fft_rate default 15 works on my 1 GHz Powerbook G4. To run the waterfall spectrum display demo (screenshot): $ pythonw waterfallsink.py

Here is a slightly more elaborate signal/noise demo (link) : http://staff.washington.edu/jon/grosx/gr-signoise.html

Using the USRP on MAC Overview The USRP is the GNU Radio hardware. The usrp and gr-usrp modules in the GNU Radio software support the USRP.

Building gr-wxgui The usrp and gr-usrp modules are built at the same time as the other GNU Radio modules, as directed in the build configuration.

Using the USRP To use the USRP, your Mac must have a USB 2.0 port. You can check this by running System Profiler (Menu Bar Apple Icon -> About This Mac -> More Info ...). Under Hardware click on USB, under USB Device Tree there should be an entry USB High Speed Bus. Older Macs do not have a USB 2.0 port. My 1 GHz G4 Powerbook only has USB 1.1 (purchased Summer 2003, apparently the last Mac without USB 2.0). I obtained one of the USB 2.0 add-in cards recommended by Apple: the Belkin F5U222. It plugs into the Powerbook's cardbus slot and is automatically recognized by OS X; it is not necessary to install any drivers or do any other configuring. Power up the USRP and plug its USB cable into one of the Mac's USB 2.0 ports. Before you run any GNU Radio USRP programs, the Mac should detect the USRP's presence, as shown in the System Profiler (screenshot).

The first time you run any USRP program, the GNU Radio software downloads FPGA code into the USRP. After that, the Mac recognizes the USRP (screenshot).

There are programs for testing and demonstrating the USRP in the installed GNU Radio directories in gr/bin usrp_siggen.py Signal generator usrp_oscope.py Oscilloscope (screenshot)

usrp_fft.py

Spectrum analyzer (screenshot)

Use the -h option to see the command line options, for example pythonw usrp_oscope.py -h (the USRP doesn't need to be connected for this). You can run usrp_siggen and usrp_oscope (or usrp_fft) at the same time (starting them from different terminal windows), connecting the TX output from one to the RX input of the other. In December 2005, GNU Radio + USRP on the Mac achieved throughputs of 2 to 4 MBytes/sec, which is sufficient for transfering audio frequency signals between the Mac host and the USRP: http://lists.gnu.org/archive/html/discuss-gnuradio/2005-12/msg00225.html To cope with these throughputs, you must use the -i (interpolation) argument for TX output, or the -d (decimation) argument for RX input. For example:

python usrp_siggen.py -i256 pythonw usrp_oscope.py -g0 -f0 -d256 UPDATE: Faster USB support is now included in the GNU Radio usrp module, so you might see better performance than reported above: http://lists.gnu.org/archive/html/discuss-gnuradio/2006-05/msg00027.html

IMPORTANT NOTES:

Make sure that the version of SDCC is at least 2.8.0; previous versions had runtime issues on Intel-Macs. GNU Radio release 3.2 requires Python 2.5 or 2.6; version 2.4 and prior have issues with threading that were resolved in 2.5 . The internal hardware on PPC-Macs was not designed for high throughput USB 2.0, and thus no PPC-Mac has been tested at 32 Mega-Bytes/second (MBps) using a USRP and the native USB hardware; close to 32 MBps can be achieved using PCCard/PCMCIA- or PCI-based USB 2.0. The internal hardware on Intel-Macs is much better designed to handle USB 2.0, and hence even a 20" iMac can achieve 32 MBps.

NetBSD installation guide


These instructions should work for most systems using pkgsrc (such as DragonflyBSD).The most recent release of GNU Radio is usually available in pkgsrc: http://www.netbsd.org/docs/software/packages.html , currently meta-pkgs/gnuradio. An easy way to get most of the dependencies installed in order to build from SVN is to build the GNU Radio meta-pkg. It can then be deleted, or left in place. As of 2006-10, the GNU Radio sources build with BSD make as well as GNU make. In case of mysterious failures, try GNU make and report the bug. To use dependencies provided by pkgsrc, one must pass CPPFLAGS and LDFLAGS to configure. Programs not built by pkgsrc should not be placed in /usr/pkg, so use a different prefix. ./bootstrap.sh LDFLAGS="-L/usr/pkg/lib -R/usr/pkg/lib" CPPFLAGS="-I/usr/pkg/include" ./configure -prefix=/usr/gnuradio make sudo make install To run "make distcheck", one must pass LDFLAGS and CPPFLAGS as above because distcheck runs configure after creating a tarball and unpacking it. To run "make check", one must have large amounts of space free in /tmp (over 128 MB?) One can do "TMP=/usr/tmp make check" after creating another tmp dir to work around this problem. (Note: the links below do no longer work. BBN Technologies was acquired by Raytheon in 2009. The ADROIT project seems defunct and the relevant web servers no longer work) Support for improved USB speed was committed to NetBSD-current in July, 2006. This code is also in the netbsd-4 branch. Code to use the new USB driver enhancements was committed to GNU Radio svn in September, 2006 prior to the creation of the 3.0 release branch. Documentation of speed tests of the USB code are at the ACERT ADROIT GNU Radio project CVS repository: http://acert.ir.bbn.com/viewvc/adroitgrdevel/adroitgrdevel/radio_test/usb/ . See also the main project page. https://acert.ir.bbn.com/projects/adroitgrdevel/ The vmcircbuf tests use large amounts of sysv shm resources because 64 mapping objects are created and then all are freed.

GNU Radio for Windows users

Currently, there are no up-to-date binaries available for Windows. You will need to install GNU Radio from source. For this, refer to the windows install guide.

Current Windows Status Installing GNU Radio and USRP on Windows is not yet routine. Please report any success or failures. Patches and enhancements are especially welcome! New: You can build gnuradio with the MSVC compiler using the cmake branch: CMakeWork: http://gnuradio.org/redmine/projects/gnuradio/wiki/CMakeWork

Windows Porting Issues Considerable effort has been put into making the GNU Radio code portable among various operating systems, but there are several reasons why it cannot be "simply" compiled and run under Windows:

The build and install procecures are based on Linux scripts and tools Several third-party libraries are used, each with its own, often system-dependent, installation procedure Most GNU Radio applications must interface to hardware (e.g., a sound card or USRP) which require system-dependent drivers and installation procedures Because GNU Radio is written as an extension to Python, there are potential problems on Windows if different runtime libraries are used for GNU Radio and Python

The following sections show how these issues can be addressed.

Installation Options GNU Radio is designed to be flexible. It has a number of modules, capabilities, and options that can be enabled or disabled to suit the needs of the user, and the user can add custom blocks or modules to the system.

To support this flexibility, it comes with a set of files and scripts to be used with GNU software build tools (sh, make, autoconf, automake, etc.). These tools use Linux-like commands and filenames that are not normally available on Windows systems. Fortunately, we are not the first to face this problem, and several solutions exist. These are presented in order of increasing difficulty:

Cygwin Cygwin (http://www.cygwin.com/) is a Linux-like environment for Windows. It provides the Linux-like shell, file naming, and build tools we need and also makes it easy to install many of the third-party libraries required by GNU Radio. It also provides a Linux programming interface (API); this is not required by GNU Radio, but it lets us use the bettertested Linux versions of some functions. Because the Linux API uses its own C runtime library, it is best to use Cygwin versions of Python and the third-party libraries when building GNU Radio with Cygwin. For detailed installation instructions using Cygwin see Installing GNU Radio with Cygwin :

Installing GNU Radio with Cygwin The easiest way to install GNU Radio on Windows is to use the Cygwin (http://www.cygwin.com) environment. Once Cygwin and the required utilities and third-party libraries are installed, installation of GNU Radio is as easy on Windows as it is on Linux. These instructions are for release 3.3.0 and are current as of December 19, 2010. They cover installation of the core GNU Radio components and components for using the USRP, wxPython GUI, and PortAudio. They do not cover installation of components needed for USRP2, GRC, SDL video, or the Qt GUI. FIXME: The instructions for installing from the latest repository are completely out-of-date. To install GNU Radio with Cygwin you need to: 1. 2. 3. 4. Install the Cygwin environment Install the required utilities and third-party libraries Build and install GNU Radio Install the driver for the USRP (if you have a USRP)

Installing Cygwin Installing Cygwin is easy, but there are a few details to worry about; see getting started with Cygwin. If you have previously installed Cygwin, you should check to see that your packages are up-to-date.

Getting Started with Cygwin This page tells you how to:

install Cygwin start a command prompt window running a Cygwin (i.e., bash) shell install, update, or remove packaged utilities and libraries using Cygwin's setup.exe understand how Cygwin works with Windows and how using Cygwin is different from using Linux find further information on using Cygwin

Installing Cygwin Installing Cygwin is simple, but you must have administrator privileges for the initial installation, and you must either have administratior privileges or be the owner of the Cygwin registry entries to install Cygwin packages. If you normally run with limited user privileges: Managing your Cygwin installation is easier if you are the owner of the Cygwin entries in the Windows registry.The way to ensure this is to: 1. Log out of your usual account 2. Log into an account with administrator privileges and use the control panel to give your usual account administrator privileges 3. Switch to your usual account and install Cygwin using the procedure below 4. Log out of your usual account 5. Log into your administrator account and change your usual account back to limited user If you do this, you will own the Cygwin entries in the registry. If you do not do this, you will need administrator privileges to install Cygwin packages. There is also an option during the installation process to install Cygwin for "Just Me". This may be easier, but I have not tried it. You will still need administrator privileges if want to install a USRP.

To install Cygwin: 1. Go to http://www.cygwin.com 2. Click on "Mirror Sites" in the lefthand column and note the two mirror sites nearest you 3. Go back to http://www.cygwin.com and click on "Install Cygwin now" 4. Go ahead and run setup.exe; the default settings are fine, but you may want to make the "Local Package Directory" a subdirectory of your "Root Directory" (e.g., "C:\cygwin\setup") 5. When asked to choose a mirror site, choose one you selected above; if that one doesn't work, try the other one 6. Keep clicking "Next" until Cygwin has been installed; you probably want to click the boxes to put an icon on your desktop and add Cygwin to your startup menu For convenience you may want to go back to http://www.cygwin.com, right-click on "Install Cygwin now" again, and save a copy of setup.exe in a convenient place (e.g., C:\cygwin\setup\setup.exe). You will be running setup.exe repeatedly to download and update Cygwin packages.

Starting a Cygwin Window Most of the work in Cygwin is done by entering commands into a command prompt window. The commands you enter are interpreted by a GNU bash shell. You can start a Cygwin command window in one of the following ways:

Double-click on the Cygwin icon on your desktop (if setup.exe put one there) Find Cygwin in your Windows "Start" menu (under "All Programs") If necessary, you can use Windows Explorer to navigate the the Cygwin root directory (e.g., "My Computer" -> "Local Disk" -> "Cygwin") and double-click on cygwin.bat; or you can right-click on cygwin.bat and select "Send To" -> "Desktop" to make a shortcut for next time

Using setup.exe One thing that makes Cygwin convenient is the ease of selecting and installing optional software packages with setup.exe. You can run setup.exe from the web, from a command prompt, or from Windows Explorer, depending on what privileges you have. If you have administrator privileges or if you own the Cygwin registry entries, you can either:

Go to http://www.cygwin.com and click the "Install Cygwin now" icon; or Run setup.exe from your local disk (e.g., /setup/setup.exe) if you saved a copy there; or Use Windows Explorer to navigate to the directory containing your saved setup.exe (if you have one) and double-click

If you have access to an account with administrator privileges and a non-blank password, you can: 1. Use Windows Explorer to navigate to the directory containing your saved setup.exe (if you

have one) and double-click; then 2. Enter the account name and password when requested Once Cygwin Setup is running, you can tell it to use the default values (Install from Internet; same root directory, "install for" setting, and default text file type as on your initial install; same local package directory; same internet connection; and same download site) until you get to the "Select Packages" window. The "Select Packages" window is very powerful but is not immediately intutiive to all users, has no "Help" buttion, and the pop-up documentation may go away before you can finish reading it. The most important thing to know is that the "View" button cycles through several displays of packages:

Category: click the "+" to see what is in a category Full: everthing in alphabetical order Partial: your current "to do" list, including packages you have selected, other packages required by your selections, and updates to packages you installed previously Up to Date: a list of packages you already have Not Installed: a list of packages you don't already have The "Current" column shows the version number for each package you have already installed while the "New" column lets you select select a package to be installed, reinstalled, uninstalled, or kept unchanged. Normally, you will choose a convenient View (e.g., "Category" or "Not Installed") to select packages then chose the "Partial" view to verify the changes you are about to make. Clicking "Next" will make the changes you selected.

Cygwin vs. Linux; Cygwin and Windows Although Cygwin uses a bash shell and many of the same commands and programs as Linux, it is still running under the Windows operating system and must accommodate the needs and limitations of that system. Some of the important consequences are:

File and Path Names

Windows remembers the case of characters in filenames, but ignores the case when accessing files; any files sent back to a Linux system will use the case you specify, so it pays not to be too sloppy Windows uses "\" to separate directories in a path, but in Cygwin you must use "/" (the bash shell uses "\" as an escape character) Path names starting with "/" are relative to the Cygwin root directory (i.e., C:/cygwin for a default installation) Non-Cygwin files can be accessed with their full Windows path (starting with the drive letter) using "/" instead of "\"; if a path includes spaces, enclose it in double quotes (e.g., ls "C:/Program Files/SDCC") The "C:" in a path should be replaced with "/cygdrive/c" when the ":" might cause a problem (e.g., PATH="$PATH:/cygdrive/c/Program Files/SDCC") To access Cygwin files from Windows, start by navigating to your Cygwin installation directory (e.g., "My Computer" -> "Local Disk(C:)" -> "cygwin" in a default installation) Executable files on Windows have names ending in .exe but you can reference them in Cygwin without the .exe; thus the ls command actually runs /bin/ls.exe and ls /bin/ls shows the file /bin/ls even though the file is actually named /bin/ls.exe

End-Of-Line Conventions; Binary and Text Files In Linux, lines in a text file are separated by a newline characters (ASCII Ctrl-J, often shown as !^J, or '\n' in C). In Windows, lines are separated by carriage return and newline characters (the two-character sequence ^J or "\r\n" in C). Many of the programs you will use with Cygwin don't care, but some do. When you see !^M popping up you know that there are Windows-style files around. When you look at a file in Windows Notepad and see all the lines running together with little boxes between them you know you are looking at a Linux-style file. In general, when working on programs with Cygwin it is better to stick with the Linux \n line separators when possible. In particular, the Cygwin autoconf utility has problems with some .m4 files that include the !^M characters as line separators. This also means that it is better to use a Cygwin version of the Subversion program rather than a Windows version---the Windows version will give you the extra !^M characters with some files in some SVN repositories.

Permissions The Linux su and sudo commands do not work on Cygwin. On Windows, access to some files and to parts of the Windows registry (a database of system configuration information) is limited to accounts with administrator privileges. Most files in Cygwin can be accessed without administrator privileges. Many Windows systems are set up with administrator privileges on normal user accounts, but many users with Unix or Linux backgrounds prefer to work mostly as what Windows calls limited users. If you normally work in a limited user account and you need to access resources that require administrator privileges, you must to one of the following:

Use an account with administrator privileges to access the resources, or Use an account with administrator privileges to temporarily give administrator privileges to your account; you will need to log into your account again for the changes to take effect, or Most programs can be run as another user by right-clicking on them (in Windows Explorer) and selecting "Run as..." (some programs, such as Cygwin setup.exe, automatically offer to let you run as another user); in order to use this feature, you need access to an account with administrator privileges that has a non-blank password

Where to Find More Infomation on Using Cygwin The best places to start are the Cygwin FAQ and User's Guide. Both are available at http://www.cygwin.com, and they should also be installed on your machine (look under "Cygwin" in your "Start" -> "All Programs" menu). The User's Guide includes sections for Windows users who are new to Linux and Linux users who are new to Windows.

Installing Utilities and Third-Party Libraries Utilities and third-party libraries are of two types: those that are available as Cygwin packages and those that must be downloaded and/or built separately. apt-cyg(http://stephenjungels.com/jungels.net/projects/apt-cyg/ ) may help you installing. It works like aptitude, so you can install and search packages from the command line.

Installing Cygwin packages You will need the following Cygwin packages to build GNU Radio. For instructions on installing Cygwin packages see getting started with Cygwin:

cppunit 1.12.0-1 (1.12.1 doesn't work) gcc-g++ (3.4.4 works, but 4.3.4 does not) gsl-devel guile libfftw3-devel libtool (version 2.2 or later; see hints, tips, known, problems, and solutions for Windows: http://gnuradio.org/redmine/projects/gnuradio/wiki/WindowsTips make patch pkg-config python (instructions below assume you have python 2.6) python-numpy swig util-linux

In order to use a USRP you will also need:

libusb-win32

If you want to install from SVN you will need:

subversion

FIXME: GNU Radio now uses git instead of subversion. Other libraries and utilities Some of the libraries and utilities required by GNU Radio are not available as Cygwin packages. These packages must be installed manually:

boost: see instructions in hints, tips, known problems, and solutions for Windows: http://gnuradio.org/redmine/projects/gnuradio/wiki/WindowsTips wxPython: not required for all applications, but extremely useful; see installing wxPython: http://gnuradio.org/redmine/projects/gnuradio/wiki/WxPythonCygwin

If you need simultaneous capture and play of audio from your sound card or have difficulties with the basic audio support, you may want:

PortAudio: see installing PortAudio: http://gnuradio.org/redmine/projects/gnuradio/wiki/PortAudioInstall

If you have a USRP you will also need:

SDCC (Small Device C Compiler); see installing SDCC on Windows: http://gnuradio.org/redmine/projects/gnuradio/wiki/SDCCInstallWindows

Building and Installing a GNU Radio Release GNU Radio can be built either from a release tarball (more stable) or from the latest code in the git repository (latest features). This section describes how to build from the release tarball. Additional considerations when building from the git repository are described later.

Downloading the Release Source Code Download the latest release of the GNU Radio source code from ftp://ftp.gnu.org/gnu/gnuradio/gnuradio-3.3.0.tar.gz to a convenient working directory. Be sure that the name of your working directory does not contain any spaces. Unpack the tarball with $ tar -zxf gnuradio-3.3.0.tar.gz to produce the directory gnuradio-3.3.0.

Preparing to Build You must specify where to find the pkg-config configuration files: $ export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig

Building a Minimal GNU Radio System GNU Radio is a large system with many options. The simplest build procedure configures and builds all the modules that it can, but you can customize your installation (and maybe save some time) by specifying appropriate options. For a first test, it is helpful to build a minimal GNU Radio. This is done with the commands:

$ cd gnuradio-3.3.0 $ ./configure --disable-all-components --enable-gruel --enable-gnuradio-core --enable-gr-audio-oss

This disables all components except those explicitly enabled, namely gruel, gnuradio-core, and gr-audio-oss. To build and install these components use the commands: $ make $ make check $ make install You may get warning messages, but unless one of these commands stops with an error message you should have a working installation of GNU Radio. If you do get errors be sure to check hints, tips, known problems, and solutions for Windows( see links above). If an older version of GNU Radio was installed previously, you should remove it with make uninstall before you get to make check. To actually make GNU Radio do something, try: $ export PYTHONPATH=/usr/local/lib/python2.6/site-packages $ cd gnuradio-examples/python/audio $ python dial_tone.py This should produce a dial tone through your speakers. If Python gives you an error message, there is a problem with your installation of GNU Radio. If you get no error messages but no sound, check to see that your speakers are turned on, your volume is turned up, and that the "Wave" source is enabled in your audio control panel. Use Ctrl-C to stop the dial tone. If dial_tone.py stops by itself without producing sound or gives a Windows error pop-up, your version of Cygwin may be out of date (see hints, tips, known problems, and solutions for Windows above). The PYTHONPATH environment variable must be set to tell Python where to find the GNU Radio extension modules. With this minimal GNU Radio system you can capture signals from your sound card, read signals from a file, or generate signals; process signals; and play signals on your sound card or save them to a file. Note that you cannot simultaneously capture and play signals using the same sound card with gr-audio-oss.

Building a Full GNU Radio System Building a full GNU Radio system is simpler but takes longer: $ cd gnuradio-3.3.0 $ ./configure This enables all components for which the required libraries and utilities are available. To build and install these components use the commands: $ make $ make check $ make install Unless one of these steps fails due to an error, you should have a working GNU Radio installation. If one of the steps fails, you may be able to disable the component that failed. Use ./configure --help to see how the components are named. Look for the "--enable-..." options and add the corresponding "--disable-..." option to your ./configure command and repeat the above steps. If an old version of GNU Radio is installed, you should remove it with make uninstall before doing make check. Note that make check sometimes fails on Cygwin due to problems with "sem_init" or "allocate_lock". These are Python and/or Cygwin problems, which don't affect most users of GNU Radio. Be sure that PYTHONPATH is set as above before running a GNU Radio application.

Building and Installing GNU Radio from the SVN Repository Note: These instructions are obsolete since the changeover to the git repository. If you want the latest features and are willing to deal with code that is still in development, you can check out the latest code from the subversion (svn) repository: $ svn co http://gnuradio.org/svn/gnuradio/trunk gnuradio Be sure to use the Cygwin version of subversion (available from Cygwin setup); other versions of svn for Windows may produce files with an extra CR (^M) character at the end of each line. The procedure for building the svn version is like that given above for building the release version, but because the svn version is constantly changing, there may be extra requirements a need for patches. Note that the lists of requirements and patches may become out of date at any time.

Extra requirements:

none known at this time

The following patches are needed:

no patches are needed as of 25 Aug 2008

To apply a patch, follow the link to the listing of the patch file and download it to your gnuradio directory using the Original Format link at the bottom of the page. Then use the command $ patch -p0 -b -i file.patch (replacing file.patch with the name of the patch file) to apply the patch. After applying any patches and before running ./configure you must initialize the build with $ ./bootstrap and you must set the necessary environment variables: $ export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig The remainder of the build process is the same as for the release version except that boost should be found automatically in /usr/local/include: $ ./configure $ make $ make check $ make install Be sure that no older version of GNU Radio is installed when running make check. Expect `make check` to fail in test_inband.exe with "uncaught exception of type mbe_mblock_failed" errors; see Issue #191(http://gnuradio.org/redmine/issues/191 ) for details.

Installing the Driver for the USRP If you have a USRP you will need to install the driver for it; see installing the USRP driver for Windows:

Installing the USRP Driver on Windows

The USRP driver consists of three files:


gnuradio/usrp/usrp.inf /usr/lib/libusb/libusb0.sys /usr/bin/cygusb0.dll You can simplify the installation process by putting all three files in the same place: $ cd gnuradio/usrp $ cp /usr/lib/libusb/libusb0.sys . $ cp /usr/bin/cygusb0.dll libusb0.dll

You must have administrator privileges to complete the driver installation. You must either be logged into an account with administrator privileges or have access to an administrator's account with a password. Plug in the USRP and connect it to the computer with the USB cable. You should get a balloon announcing "Found New Hardware". If you do not have administrator privileges, you may get a window requesting a user name and password allowing you to log into an account that does. One you have administrator privileges, you should get a "Found New Hardware Wizard" window. This wizard will ask a series of questions that should be answered as follows:

No, not this time (do not connect to Windows Update) Install from a list of specific location (Advanced) Search for the best driver o uncheck "Search removable media" o Include in the search the Windows path to your gnuradio/usrp directory The New Hardware Wizard should find the three files listed above and install the USRP driver.

Notes: (1) You can check that the driver has been installed using the Windows Control Panel:

Be sure that the USRP is plugged in and connected to the computer Select "Perfomance and Maintenance" and "System" to get the "System Properties" window Click the "Hardware" tab and select "Device Manager" Find the "LibUSB-Win32 Devices" entry and click the "+" next to it; you should see an entry for "USRP filter" Right-click on "USRP filter" and select "Properties" to display the USRP filter Properties window

The device status should say "This device is working properly"

(2) If the driver is not installed correctly or if you need to reinstall the driver, go to the "Driver" tab of the USRP filter Properties window and click the "Update Driver" or "Uninstall" buttons. (You must have administrator privileges to do this.) You can then disconnect the USRP and reconnect it to restart the New Hardware Installation Wizard.

Alternative Method for x386 PC: You can install the binary for LibUsbWin32(http://gnuradio.org/redmine/projects/gnuradio/wiki/LibUs ) from http://libusb-win32.sourceforge.net/ and then you can install USB in automatic mode.

Where to Go From Here Now that your GNU Radio system is installed, it is time to start exploring. The best way to learn about GNU Radio is to study and modify the examples in the various subdirectories of gnuradio-3.3.0/gnuradio-examples/python and gnuradio-3.3.0/gnuradio/gr-utils/src/python.

MinGW/MSYS MinGW (http://www.mingw.org/) provides GNU compilers and Window-specific header files for compiling native Windows applications. MSYS (http://www.mingw.org/msys.shtml) is a companion set of Linux-like commands, shell, and build tools. MinGW does not include a Linux programming interface; programs should be smaller and faster than with Cygwin (in theory), but will require more Windows-specific code. MSYS is intended primarily as a build environment, making it more compact than Cygwin. Because there is no Linux API emulation, GNU Radio built with MinGW should be used with standard Windows versions of Python and the third-party libraries. MinGW does not provide as much support as Cygwin for installing third-party libraries, but in many cases precompiled binaries are available. For detailed installation instructions using MinGW and MSYS see Installing GNU Radio with [[MinGW]].

Building on Windows with Native Tools In principle, it should be possible to build and install GNU Radio on Windows using your choice of compiler (Microsoft, Borland, GNU, etc.) and build tools (IDE or scripting languages). There is an attempt in progress described on the WindowsNativeInstall page. http://gnuradio.org/redmine/projects/gnuradio/wiki/WindowsNativeInstall Pre-built Binaries for Windows In the future, we may be able to package pre-built binary files for Windows. This would make installation easier, but might preclude users from modifying or adding signal-processing blocks or modules.so refer sometimes a year here : http://gnuradio.org/redmine/projects/gnuradio/wiki/WindowsInstall

OK, it's installed, what now? If the installation worked without any trouble, you're ready to use GNU Radio. If you have no idea how to do that, read how to use GNU Radio. You probably want to connect some Hardware to your computer to try and receive or transmit stuff. If you or your group would like to get a professional jump start on using GNU Radio and the USRP, Corgan Enterprises LLC (http://corganenterprises.com )offers a 3-day, hands-on training class (http://corganenterprises.com/wiki/GNU_Radio_Training ), to be held at your own location.

How to use GNU Radio


Even after successfully installing GNU Radio, it might not be clear what exactly GNU Radio is cabable of and what it can be used for.here is an overview of what you can do with GNU Radio and how to do it.

Using the included tools and utility programs


GNU Radio comes with a large variety of tools and programs which can be used out of the box. If you installed from source, you can find most of the source files in gr-utils/src/python and gruhd/apps.

The most commonly used tools include


uhd_fft.py - A very simple spectrum analyzer tool which uses a connected UHD device (i.e., a USRP) to display the spectrum at a given frequency. uhd_rx_cfile.py - Record an I/Q sample stream using a connected UHD device. Samples are written to a file and can be analysed off-line at a later time, using either GNU Radio or other tools such as Octave or Matlab. uhd_rx_nogui.py - Receive and listen to incoming signals on your audio device. This tool can demodulate AM and FM signals. uhd_siggen{_gui}.py - Simple signal generator, can create the most common signals (sine, sweep, square, noise). usrp_oscope.py - A simple oscilloscope using a connected USRP. gr_plot*.py - This is an entire suite of apps which can display pre-recorded samples saved to a file. You can plot the spectra, PSD and time-domain representations of these signals.

If you're using Linux, you can call all these apps from the command line. All apps include a "-h" switch which will display a help screen. With the uhd_fft.py tool, this would look like this:

$ uhd_fft.py --help linux; GNU C++ version 4.5.2; Boost_104200; UHD_003.003.000-d5d448e Usage: uhd_fft.py [options] Options: -h, --help show this help message and exit -a ADDRESS, --address=ADDRESS Address of UHD device, [default=addr=192.168.10.2] -A ANTENNA, --antenna=ANTENNA select Rx Antenna where appropriate -s SAMP_RATE, --samp-rate=SAMP_RATE set sample rate (bandwidth) [default=1000000.0] -f FREQ, --freq=FREQ set frequency to FREQ -g GAIN, --gain=GAIN set gain in dB (default is midpoint) -W, --waterfall Enable waterfall display -S, --oscilloscope Enable oscilloscope display --avg-alpha=AVG_ALPHA Set fftsink averaging factor, default=[0.1] --ref-scale=REF_SCALE Set dBFS=0dB input value, default=[1.0] --fft-size=FFT_SIZE Set number of FFT bins [default=1024] This is what it looks when used with a USRP1 and a DBSRx daughterboard observing a GSM downlink: $ uhd_fft.py -a type=usrp1 -f 935M -s 2M

Graphical signal processing development: The GNU Radio Companion (GRC) Digital signal processing (DSP) is where GNU Radio shines; this is what it was originally made for. GRC is a Simulink-like graphical tool to design signal processing flow graphs. If you're comfortable dealing with FIR filters, digital modulators and other DSP concepts, using GRC should be simple and straightforward for you.some GRC Examples are mentioned here: http://www.oz9aec.net/index.php/gnu-radio/grc-examples On Linux systems, GRC is invoked by calling the gnuradio-companion command. If your installation was fine, GRC will pop up in its own window. On the right hand side, you can find all the available blocks (good news: adding new blocks is not terribly difficult!), which can be dragged into the main window and connected by clicking the edges. Here's an example of a narrowband FM receiver, which filters a signal, FM demodulates it and passes it to the sound card (this and other examples can be found on www.oz9aec.net).

GRC Requirements Most (if not all) of these requirements can be found in the package manager of you linux distribution. [Python 2.5 (or above) http://www.python.org/download/] [Python-LXML 2.0 (or above) http://codespeak.net/lxml/installation.html] [Cheetah Template Engine 2.0 (or above) http://www.cheetahtemplate.org/download.html] [Python-GTK 2.10 (or above) http://www.pygtk.org/downloads.html] GNU Radio Requirements GRC is bundled with the current gnuradio trunk and will be included in the 3.2 release. I recommend configuring your GNU Radio installation with wx-python, usrp, and audio support. However, any configuration will work. Follow the build-guide Note: GRC will let you generate flow graphs with components that are not included in your local install. For example, you can generate a flow graph with a usrp source, but the code will error when executed unless GNU Radio is configured with usrp support.

Installing GRC GRC is bundled with gnuradio, so following the installation guide should be enough to install GRC. However, GRC will not be installed if you were missing any of the required components. Install any missing components and re-run configure/install: ./configure make sudo make install GRC should appear in the list of configured components; if not, read the configure verbose for errors. Installing Documentation To view the blocks' documentation from inside GRC, install doxygen and configure gnuradio with doxygen support: ./configure --enable-doxygen make sudo make install

Installing Icons, Mime Type, and Menu Items If you have an operating system that supports the freedesktop.org standards (Gnome, KDE, XFCE), then you may install the icons, mime type, and menu items bundled with GRC. After installing GRC, run the following command: cd <prefix>/libexec/gnuradio/ sudo grc_setup_freedesktop install -- OR for older versions -sudo grc_setup_freedesktop install Execution GRC installs several executable python files into your system's path. Executing the Flow Graph Editor Open a terminal and enter the following: gnuradio-companion -- OR for older versions -grc Executing the USRP Probe Application GRC provides a GUI app to probe the USRP for daughter-board information. Open a terminal and enter the following: usrp_probe Executing the USRP2 Probe Application GRC provides a GUI app to probe the USRP2 for daughter-board information. Open a terminal and enter the following: usrp2_probe

Usage Tips

Add a block: double click on a block in the block selection window. Connect blocks: click on the port of one block, then click on the port of another block. Remove a connection: click on the connection, press delete, or drag the connection to remove. Edit block parameters: double click on a block in the flow graph. Select a block, hit up/down for quick type change. For more short cuts, see the hot keys in the menu. Flow graphs that are completely simulation (without audio or usrp blocks) will consume 100% CPU when executed, and the GUI elements will be unresponsive. These flow graphs must include a Misc->Throttle block to throttle the rate of the streaming data.

Variables Variables map symbolic names to values. In GRC, a variable can define a global constant or, a variable can be used in conjunction with a GUI to control a running flow graph. Variable Block The variable block is the most basic way to use a variable in GRC. The ID parameter of the variable block is the "symbolic name". The symbolic name must be alpha-numeric (underscores allowed) and begin with a letter. To use the variable, simply enter the symbolic name into a parameter of another block. Variable Controls Certain blocks have callback methods that allow their parameters to be changed while executing flow graph. Variable controls in GRC use variables in combination with callback methods to modify these parameters. If a parameter has a callback method, the parameter will be underlined in the block-properties dialog. The variable slider, variable text box, and the variable chooser block provide graphical widgets such as sliders, text boxes, radio buttons, and drop downs as variable controls. In addition, the variable sink block takes samples from a gnuradio stream and writes the samples to a variable. String Evaluation String parameters have a two-phase evaluation. First, GRC evaluates the parameter as-is. If the parameter does not evaluate to a string data type or the evaluation fails, then it is understood that the parameter had implied quotation. In this case, GRC will evaluate the parameter again with quotation marks; which will return a string with the exact code that was typed into the parameter window.

To use a variable inside a string simply type the name of the variable into the parameter: my_var. If the variable is not a string, cast the variable with python's str function: str(my_var). Standard python string functionality applies: "My Var = " + str(my_var). Note: String parameter types also include the file open and file save types.

Filter Design Many blocks in gnuradio that take an array of complex or real taps as a parameter. GNU Radio provides a package to generate all kinds of filter and window taps. http://gnuradio.org/doc/doxygen/classgr+firdes.html

Firdes Taps Generators


low_pass(gain, samp_rate, cutoff_freq, width, [window], [beta]) high_pass(gain, samp_rate, cutoff_freq, width, [window], [beta]) band_pass(gain, samp_rate, low_cutoff_freq, high_cutoff_freq, width, [window], [beta]) complex_band_pass(gain, samp_rate, low_cutoff_freq, high_cutoff_freq, width, [window], [beta]) band_reject(gain, samp_rate, low_cutoff_freq, high_cutoff_freq, width, [window], [beta]) gaussian(gain, spb, bt, int ntaps) hilbert(int ntaps, window, beta) root_raised_cosine(gain, samp_rate, symbol_rate, alpha, int ntaps) window(window, int ntaps, beta)

Firdes Window Types


WIN_HAMMING WIN_HANN WIN_BLACKMAN WIN_RECTANGULAR WIN_KAISER

Firdes Notes For the pass band functions, window defaults to the Hamming window. The beta parameter defaults to 6.76, and only applies to the Kaiser window.

Firdes Usage Example Create a new "import" block, and enter the following for the import parameter: from gnuradio.gr import firdes Note: Most blocks with a taps parameter automatically import the firdes module. You only need to use the import block when firdes will not evaluate. Enter the following into the taps parameter of a filter block: firdes.low_pass(1.0, samp_rate, 1000, 100, firdes.WIN_HAMMING) Use Taps from a File Suppose that you have an array of filter taps stored in a file that you would like to use inside GRC: Create a new "import" block, and enter the following for the import parameter: import numpy Enter the following into the taps parameter of a filter block: numpy.fromfile('taps file path', numpy.complex64) This will read an entire binary file and parse every 64 bytes into a complex number. Use numpy.float32 for real taps. See the numpy.fromfile help for more advanced usage: Help on built-in function fromfile in numpy: numpy.fromfile = fromfile(...) fromfile(file=, dtype=float, count=-1, sep=_) -> array. Required arguments: file -- open file object or string containing file name. Keyword arguments: dtype -- type and order of the returned array (default float) count -- number of items to input (default all) sep -- separater between items if file is a text file (default "") Return an array of the given data type from a text or binary file. The 'file' argument can be an open file or a string with the name of a file to read from. If 'count' == -1 the entire file is read, otherwise count is the number of items of the given type to read in. If 'sep' is "" it means to

read binary data from the file using the specified dtype, otherwise it gives the separator between elements in a text file. The 'dtype' value is also used to determine the size and order of the items in binary files. Grid Positioning GRC offers several graphical sinks and graphical controls for creating wx-gui flow graphs. (scope sink, fft sink, number sink, waterfall sink, constellation sink, slider control, and chooser control) Each of these graphical elements have a grid position parameter for precise positioning. A grid position parameter is a list of 4 integers of the form (row, column, row span, column span). The row and column specify the position of the upper-left corner of the graphical element. The smallest position, the (0, 0) position, specifies the upper-left corner of the grid. If left blank, the grid parameter specifies that the graphical element will be automatically stacked into a vertical sizer. The vertical sizer is positioned directly above the grid sizer. If you do not want any elements to be added to the vertical sizer, leave no grid parameters blank. The row and column span specify the stretch, or the number of rows and columns that the graphical element can occupy. The row span specifies the number of rows down from the row positon, and the column span specifies the number of columns right of the column position. Therefore, the span must be at least (1, 1) to occupy the minimum of 1 grid cell. Example The user wishes to place a slider, centered directly above a graphical sink. The slider will be positioned at the 2nd column of the top row and with a column span of 2. The sink will be positioned on the 2nd row, and with a row span of 2 and a column span of 4. Notice the grid parameters below, and the resulting gui layout: The Elements:

Slider Control: (0, 1, 1, 2) Graphical Sink: (1, 0, 2, 4)

The Resulting GUI: 0,0 0,1 0,2 0,3 1,0 1,1 1,2 1,3 2,0 2,1 2,2 2,3

Hierarchical Blocks GRC can create hierarchical blocks out of the built-in blocks. Hierarchical blocks can be instantiated inside of other grc flow graphs. The python code generated from a hierarchical block can itself be used in non-GRC flow graphs. Four important blocks are used in the creation of a hierarchical block: The options block, parameter blocks, and the pad source and pad sink. The Options Block In order to make a hierarchical block, the parameters in the options block must be set properly. The id of the options block sets the module name, and must be unique among the entire library of blocks (built-in and custom). The title parameter sets the display name for the block. The generate options must be set to "Hier Block". The category parameter sets the category for the new block. This category can be an existing category in the block selection window or a new category. Categories may be nested by specifying a name with slashes, ex: Custom/Filters. To put blocks into the root category, specify a single slash "/" (a blank category will hide your block). Parameter Blocks Parameter blocks specify variables in your hierarchical block that should be configurable in the top level block. Parameter blocks work much like variable blocks with a few exceptions: Parameters blocks cannot depend on variable blocks or other parameter blocks. Parameter blocks have a label parameter for display purposes. Parameter blocks take the place of a variable block, do not try to create a variable block with the same id as your parameter block. Pad Source and Sink Blocks The pad source and sink blocks create inputs and outputs for the hierarchical block. The pad blocks have configurable data types, vector lengths, and number of ports. A flow graph can have at most, one pad source, and one pad sink. A hierarchical block may have one pad sink and no pad source or no pad sink and one pad source, but it must have at least one pad block. Creating and Instantiating

Start with a blank slate and create a new (empty) flow graph. Setup the options block as described above, with the id, title, generate options, and category. Add parameter blocks for all variables you wish to configure/control outside of the block. Create at most one pad source and one pad sink to match the IO type and connect them. When finished, click the generate button, and close/reopen GRC. The hierarchical block will appear in the block selection window. Add the hierarchical block to a flow graph as your would any other block.

Notes

After making changes to your hierarchical block, make sure to regenerate, and reopen GRC before usage. The ID parameter of the block must be unique. If two blocks share the same ID, the last one to be generated will overwrite the other. Custom hierarchical blocks may instantiate other custom hierarchical blocks. Just don't have a block instantiate itself!

Adding Custom Blocks Every block in GRC corresponds to an XML file that describes the block's parameters, inputs, outputs, and other attributes. Adding a custom block into GRC is simply a matter of creating one of these XML block definition files. A few caveats:

The block should be accessible from the python path. Meaning that the block can be accessed via an import statement. The block follows the block diagram model: it has parameters, inputs, and outputs. If the block requires some kind of listening thread, or special callback methods to move the data (as in the blks2 packet stuff), it cannot be used in GRC (unless this "special" functionality can be encapsulated into a block that is block-diagram-safe). If GRC is missing a block definition for a block that is currently in the trunk, or one of the block definitions is missing functionality, please mail the list. The block definitions in the GRC trunk must stay in sync with the actual GNU Radio blocks.

Creating the XML Block Definition The best way to learn how to create the xml file is to learn by example. See the block definitions (source:grc/blocks): http://gnuradio.org/redmine/projects/gnuradio/repository/entry/grc/blocks packaged with GRC, and read through a few files. Essentially, all block definitions are structured as follows: <?xml version="1.0"?> <block> <name>My Block Name</name> <key>my_package_my_block_ff</key> <category>Filters</category> <import>from gnuradio import my_package</import> <make>my_package.my_block_ff($param1, $param2)</make> <callback>set_param1($param1)</callback> <param> <name>Parameter 1</name>

<key>param1</key> <type>real</type> </param> <param> <name>Parameter 2</name> <key>param2</key> <value>1</value> <type>int</type> </param> <sink> <name>in</name> <type>float</type> </sink> <source> <name>out</name> <type>float</type> </source> <source> <name>out</name> <type>float</type> </source> </block>

The example above will make a block with 2 parameters, 1 input, and 2 outputs. The ordering of the tags is important, if tags are not ordered properly, the block will fail validation. See [/trac/browser/gnuradio/trunk/grc/data/platforms/python/block.dtd block.dtd] for specifics. The name tags dictate the label text for the block, parameters, and ports. The key tags are unique identifiers, they may not contain spaces. The block key must be globally unique among all blocks in GRC. The parameter keys must be unique only within the block. The category tag is a unix-style path that represents the location of the block inside the block selection window. The path can be a new category (Custom), or represent a subcategory (Filters/Custom). To put a block into the root category, just use a single slash (/) for the root path. The import tag (there can be multiple) must be a valid python import statement to the module containing your block. The make tag contains the code necessary to construct your block. This code is essentially a cheetah template nested inside an xml tag. Upon code generation, the template performs a text substitution on the "$" parameters. For more advanced capabilities, see the cheetah template documentation. : http://www.cheetahtemplate.org/docs/users_guide_html The callback tag registers a set-method from your custom block. Once the set-method is registered, the set-method can be called at runtime when a variable is changed. There can be any number of callback tags, one for each set-method of your block. Or no callback tags if this is not applicable.

For the param tags, the commonly used values for the type tags are: complex, real, int, complex_vector, real_vector, int_vector, string, and raw. The raw type allows any value to be used without performing type checking. The real type should be used for single and double precision floating point numbers. The int type should be used for longs, ints, shorts, and chars. The sink tag represents an input port, and the source tag represents an output port. The allowed values for the type tags are: complex, float, int, short, and byte. For ports with a vector length, specify a vlen tag after the type tag.

Some Example Definitions

*Simple Example: "Complex to Real" source:grc/blocks/gr_complex_to_real.xml

http://gnuradio.org/redmine/projects/gnuradio/repository/entry/grc/blocks/gr_complex_to_re al.xml

*Multiple Callbacks: "Costas Loop" source:grc/blocks/gr_costas_loop_cc.xml :

http://gnuradio.org/redmine/projects/gnuradio/repository/entry/grc/blocks/gr_costas_loop_cc.xml

*Vlen Example: "Throttle" source:grc/blocks/gr_throttle.xml

http://gnuradio.org/redmine/projects/gnuradio/repository/entry/grc/blocks/gr_throttle.xml

*Advanced Make: "FFT" source:grc/blocks/gr_fft_vxx.xml

http://gnuradio.org/redmine/projects/gnuradio/repository/entry/grc/blocks/gr_fft_vxx.xml

Installing the XML Block Definition There are many methods to tell grc about your new xml file. Choose one of the following methods...

Method 1: Default Hier Block Location Create the .xml file inside *~/.grc_gnuradio/ where ~ is your home directory. If the directory does not exist, create it: mkdir ~/.grc_gnuradio/

Method 2: Configuration File Create or edit ~/.gnuradio/config.conf and add the following lines: [grc] local_blocks_path=/path/to/my/blocks The local_blocks_path can contain multiple paths separated by colons: local_blocks_path=/path/to/blocks1:/path/to/blocks2 Method 3: Environment Variable Set the GRC_BLOCKS_PATH environment variable to a path that contains your custom block wrapper. The GRC_BLOCKS_PATH can contain multiple paths separated by colons: GRC_BLOCKS_PATH=/path/to/blocks1:/path/to/blocks2

Using python in GNURadio project Using Python to write powerful signal processing and radio applications Sometimes GRC cannot provide all the flexibility required for your application. Anything that can be clicked together in GRC can also be written in Python, and while it is more of an effort to code everything yourself, it also provides you with the entire power and functionality of Python and its libraries, such as SciPy or NumPy for Python-centric processing of your signals or your favourite widget library to create any GUI you wish. Have a look at the Python apps tutorial to find out how to go ahead here: http://gnuradio.org/redmine/projects/gnuradio/wiki/TutorialsWritePythonApplications Before you get started with this tutorial, make sure your GNU Radio installation is ready and working. You don't necessarily need a USRP, but some kind of source and sink (USRP or audio) is helpful, although not strictly required. If the GNU Radio examples work (such as dial_tone.py in gnuradio-examples/python/audio), you're ready to go. You should also have some background in programming - but don't worry if you've never programmed Python, it is a very easy language to learn.

Understanding flow graphs Before we start banging out code, first we need to understand the most basic concepts about GNU Radio: flow graphs (as in graph theory) and blocks. Many GNU Radio applications contain nothing other than a flow graph. The nodes of such a graph are called blocks, and the data flows along the edges. Any actual signal processing is done in the blocks. Ideally, every block does exactly one job this way GNU Radio stays modular and flexible. Blocks are written in C++; writing new blocks is not very difficult (but explained elsewhere). The data passing between blocks can be of any kind - practically any type of data you can define in C++ is possible. In practice, the most common data types are complex and real short or long integers and floating point values as most of the time, data passing from one block to the next will either be samples or bits.

Examples In order to illuminate this diffuse topic a little, let's start with some examples: Low-pass filtered audio recorder +-----+ +-----+ +----------------+ | Mic +--+ LPF +--+ Record to file | +-----+ +-----+ +----------------+ First, an audio signal from a microphone is recorded by your PCs sound card and converted into a digital signal. The samples are streamed to the next block, the low pass filter (LPF), which could be implemented as an FIR filter. The filtered signal is passed on to the final block, which records the filtered audio signal into a file. This is a simple, yet complete flow graph. The first and last block serve a special purpose: they operate as source and sink. Every flow graph needs at least one source and sink to be able to function.

Dial tone generator +------------------------+ | Sine generator (350Hz) +---+ +------------------------+ | +------------+ +---+ | | Audio sink | +---+ | +------------------------+ | +------------+ | Sine generator (440Hz) +---+ +------------------------+ This simple example is often called the "Hello World of GNU Radio". Other than the first example, it has two sources. The sink, on the other hand, has two inputs - in this case for the left and right channel of the sound card. Code for this example is available at gnuradioexamples/python/audio/dial_tone.py.

QPSK Demodulator
+-------------+ +----------------+ +------------------+ | USRP Source +--+ Frequency sync +--+ Matched filter | +-------------+ +----------------+ +-----------+------+ | SAMPLES +-------------+------+ | Symbol demodulator | +-------------+------+ | SYMBOLS +-----------------+ +-----------------+ +------+------+ | Source decoder +--+ Channel decoder +--+ Bit mapping | +--------+--------+ +-----------------+ +-------------+ | +--------+--------+ | Application | +-----------------+

COMPLEX

COMPLEX

BITS DATA

This example is a bit more sophisticated, but should look quite familiar to RF engineers. In this case, the source is a USRP which is connected to an antenna. This kind of source sends complex samples to the following blocks. The interesting part about this kind of flow graph is that the data types change during the flow graph: at first, complex baseband samples are passed along. Then, complex symbols are gathered from the signal. Next, these symbols are turned into bits which again are processed further. Finally, the decoded bits are passed to some application which makes use of the data.

Walkie Talkie
+--------------+ +------------------+ +---------+ +------------+ | USRP Source +--+ NBFM Demodulator +--+ Squelch +--+ Audio Sink | +--------------+ +------------------+ +---------+ +------------+ +--------------+ +----------------+ +------------+ | Audio Source +----------+ NBFM Modulator +---------+ USRP Sink | +--------------+ +----------------+ +------------+

This applications consists of two separate flow graphs, both running in parallel. One of them deals with the Tx path, the other with the Rx path. This kind of application would require some extra code (outside the flow graphs) to mute one path while the other is active. Both flow graphs still require at least one source and sink, each. You can find a GNU Radio application that does this (only a bit more sophisticated) at gnuradio-examples/python/usrp/usrp_nbfm_ptt.py.

Summary This concludes the chapter about flow graphs. Here's a quick summary about the most vital points you really need to know:

All signal processing in GNU Radio is done through flow graphs. A flow graph consists of blocks. A block does one signal processing operation, such as filtering, adding signals, transforming, decoding, hardware access or many others. Data passes between blocks in various formats, complex or real integers, floats or basically any kind of data type you can define. Every flow graph needs at least one sink and source.

A first working code example Next step is to find out how to write those flow graphs in real Python. Let's start by examining some code line-by-line. If you are familiar with Python, you can probably skip some of the explanations, but don't rush to the next section yet - the explanations are both for Python and GNU Radio beginners.

The following code example represents the flow graph from example 2. It is actually a slightly modified version of the code example you can find in gnuradioexamples/python/audio/dial_tone.py. 1 #!/usr/bin/env python 2 3 from gnuradio import gr 4 from gnuradio import audio 5 6 class my_top_block(gr.top_block): 7 def __init__(self): 8 gr.top_block.__init__(self) 9 10 sample_rate = 32000 11 ampl = 0.1 12 13 src0 = gr.sig_source_f (sample_rate, gr.GR_SIN_WAVE, 350, ampl) 14 src1 = gr.sig_source_f (sample_rate, gr.GR_SIN_WAVE, 440, ampl) 15 dst = audio.sink (sample_rate, "") 16 self.connect (src0, (dst, 0)) 17 self.connect (src1, (dst, 1)) 18 19 if __name__ == '__main__': 20 try: 21 my_top_block().run() 22 except [[KeyboardInterrupt]]: 23 pass The first line should look familiar to anyone with some Unix or Linux background: It tells the shell that this file is a Python file and to use the Python interpreter to run this file. You need this line if you want to run this file directly from the command line. Lines 3 and 4 import necessary Python modules to run GNU Radio. The import command is similar to the #include directive in C/C++. Here, two modules from the gnuradio-package are imported: gr and audio. The first module, gr, is the basic GNU Radio module. You will always have to import this to run a GNU Radio application. The second loads audio device blocks. There are many GNU Radio modules, a short list of modules will be presented later on. Lines 6-17 define a class called my_top_block which is derived from another class, gr.top_block. This class is basically a container for the flow graph. By deriving from gr.top_block, you get all the hooks and functions you need to add blocks and connect them. Only one member function is defined for this class: the function +init+(), which is the constructor of this class. In the first line of this function (line 8), the parent constructor is called (in Python, this needs to be done explicitly. Most things in Python need to be done explicitly; in fact, this is one main Python principle).

Next, two variables are defined: sample_rate and ampl. These will control sampling rate and amplitude of the signal generators. Before explaining the next lines, have another look at the sketched flow graph chart in the previous section: it consists of three blocks and two edges. The blocks are defined in lines 13-15: Two signal sources are generated (called src0 and src1). These sources continuously create sine waves at given frequencies (350 and 440Hz) and a given sampling rate (here 32kHz). The amplitude is controlled by the ampl variable and set to 0.1. The prefix "f" of the block type gr.sig_source_f indicates the output is of type float, which is a good thing because the audio sink accepts floating point samples in the range between -1 and +1. These kind of things must be taken care of by the programmer: although GNU Radio does some checks to make sure the connections make sense, there is still some things that must be taken care of manually. For example, if you wanted to feed integer samples to audio.sink, GNU Radio would throw an error but if you would set the amplitude in the above example to anything larger than 1, you would get a distorted signal without receiving an error. The signal sink is defined in line 15: audio.sink() returns a block which acts as a soundcard control and plays back any samples piped into it. As in the blocks beforehand, the sampling rate needs to be set explicitly, even though this was set already for the signal sources. GNU Radio cannot guess the correct sampling rate from the context, as it is not part of the information flow between blocks. Lines 16 and 17 connect the blocks. The general syntax for connecting blocks is self.connect(block1, block2, block3, ...) which would connect the output of block1 with the input of block2, the output of block2 with the input of block3 and so on. You can connect as many blocks as you wish with one connect() call. Here, a special syntax is necessary because we want to connect src0 with the first input of dst and src1 with the second one. self.connect (src0, (dst, 0)) does exactly this: it specifically connects src0 to port 0 of dst. (dst, 0) is called a "tuple" in Python jargon. In the self.connect() call it is used to specify the port number. When the port number is zero, the block may be used alone. An equivalent command to the one in line 16 would thus have been 1 self.connect((src0, 0), (dst, 0)) That's all there is to create a flow graph. The last 5 lines do nothing but start the flow graph (line 22). The try and except statements simply make sure the flow graph (which would otherwise run infinitely) are stopped when Ctrl+C is pressed (which triggers a KeyboardInterrupt Python exception). For Python-beginners, two more remarks should not be left out: As you might have noticed, the class my_top_block is run without creating an instance beforehand. In Python, this is a quite common thing to do, especially if you have a class which would only get one instance anyway. However, you could just as well create one or more instances of the class and then call the run() method on the instance(es).

Second, the indenting is part of the code and not, like in C++, simply for the programmers convenience. If you try and modify this code, make sure you don't start mixing tabs and spaces. Every level must be consistently indented. If you want to go on with this tutorial, you should first get a more solid Python background. Python documentation can be found at the Python web site http://www.python.org/, or a library of your choice. A good place to start for people with prior programming experience is http://wiki.python.org/moin/BeginnersGuide/Programmers .

Summary

You need to import required GNU Radio modules with the from gnuradio import command. You always need the module gr. A flow graph is contained in a class which itself is derived from gr.top_block. Blocks are created by calling functions such as gr.sig_source_f() and saving the return value to a variable. Blocks are connected by calling self.connect() from within the flow graph class If you don't feel comfortable writing some basic Python code now, have a break and go through some Python tutorials.

The next section will give a more detailed overview about writing GNU Radio applications in Python.

Coding Python GNU Radio Applications The example above already covers quite a lot of how to write Python GNU Radio applications. This chapter and the next will try to show the possibilites of GNU Radio applications and how to use them. From now on, there is no need to linearly read these chapters section-for-section, it probably makes more sense to go over the titles and find out what you want to know.

GNU Radio Modules GNU Radio comes with quite a lot of libraries and modules. You will usually include modules with the following syntax: 1 from gnuradio import MODULENAME Some modules work a bit differently, see the following list on the most common modules.

gr usrp

The main GNU Radio library. You will nearly always need this. USRP sources and sinks and controls. Soundcard controls (sources, sinks). You can use this to send or receive audio to the sound cards, but you can also use your sound card as a narrow band receiver with an external RF frontend. This module contains additional blocks written in Python which include oftenused tasks like modulators and demodulators, some extra filter code, resamplers, squelch and so on. Routines for designing optimal FIR filters. Some functions to plot data with Matplotlib This is actually a submodule, containing utilities to quickly create graphical user interfaces to your flow graphs. Use from gnuradio.wxgui import * to import everything in the submodule or from gnuradio.wxgui import stdgui2, fftsink2 to import specific components. See the section 'Graphical User Interfaces' for more information. Adds some functions to deals with numbers in engineering notation such as @100M' for 100 * 10^6'.

audio

blks2

optfir plot_data

wxgui

eng_notation

Use from gnuradio.eng_options import eng_options to import this feature. This eng_options module extends Pythons optparse module to understand engineering notation (see above). gru Miscellaneous utilities, mathematical and others.

This is by far not a complete list, nor are the descriptions of the modules very useful by themselves. GNU Radio code changes a lot, so creating a static documentation would not be very sensible. Instead, you will have to use the good old Star Wars motto to delve further into the details of the modules: "Use the source!". If you feel GNU Radio should really already have some functionality you want to use, either browse through the module directory Python uses or go through the source directory of GNU Radio. In particular, pay attention to the directories starting with gr- in the source directory, such as gr-sounder or gr-radar-mono. These produce their own code and, consequently, their own modules.

Of course, Python itself comes with a lot of modules, some of which are extremely useful - if not necessary - to write GNU Radio applications. Check the Python documentation and the SciPy website for more information.

Choosing, defining and configuring blocks


GNU Radio comes with an abundance of pre-defined blocks, so for beginners, it is often quite confusing to find the correct blocks for their applications and set them up correctly. As with modules, the GNU Radio code changes around quite a bit, so a static documentation doesn't really make sense. However, the situation is a bit different with blocks. First of all, there's the unofficial GNU Radio manual (based on GNU Radio 3.1.1) which can be downloaded by googling Simple-Gnuradio-User-Manual-v1.0.pdf . http://rapidshare.com/files/72169239/Simple-Gnuradio-User-Manual-v1.0.pdf

Then, there's the automatically generated documentation. This is created by Doxygen from the source code. I recommend making these docs the same time as building the rest. Run ./configure with the --enable-doxygen switch for to create the docs when running make. The latter is particularly useful as it consists of multiple HTML documents which can be browsed easily. If you don't want to create the documents yourself or don't have to possibility to do so, you can find a version (although not an up-to-date one) on the web at http://gnuradio.org/doc/doxygen/hierarchy.html. The auto-generated docs are in your source directory beneath gnuradio-core/doc/html. Learning how to use these documentations is a major part of learning how to use GNU Radio! Let's get practical. Here's the three lines from the previous example which define the blocks: 1 src0 = gr.sig_source_f (sample_rate, gr.GR_SIN_WAVE, 350, ampl) 2 src1 = gr.sig_source_f (sample_rate, gr.GR_SIN_WAVE, 440, ampl) 3 dst = audio.sink (sample_rate, "") Here's a simplified version of what happens when this code is executed: First, a function called sig_source_f in the module gr is executed. It receives four function arguments:

sample_rate, which is a Python variable, gr.GR_SIN_WAVE, which is a constant defined in the @gr' module, 350, a normal literal constant, ampl, another variable.

This function creates a class which is subsequently assigned to src0. The same happens on the other two lines, although the sink is fetched from a different module (audio). So how did I know which block to use and what to pass to gr.sig_source_f()? This is where the documentation comes in. If you use the Doxygen-generated docs, click on the top left tab called "Modules". Proceed to "Signal Sources". You will find a list of signal generators, including the sig_source_* family. The suffix defines the data type at the output:

f = float c = complex float i = int s = short int b = bits (actually an integer type)

These suffixes are used for all types of blocks, e.g. gr.fir_filter_ccf() will define an FIR filter with complex input, complex output and float taps, and gr.add_const_ss() will define a block which adds incoming short values with another, constant, short int. A list of all classes with a short description can be obtained by clicking on the top tab called "Classes". The unofficial GNU Radio manual lists all classes sorted by module and can be searched using your PDF reader of choice. Most blocks you'll be using at the beginning are either from the gr, audio or usrp modules. So if you find a class called gr_sig_source_f in the auto-generated docs, you can create this class in Python by calling gr.sig_source_f(). At this point it is worth having a closer look behind the curtains of GNU Radio. The reason you can easily use the blocks - written in C++ - in your Python code is because GNU Radio uses a tool called SWIG to create an interface between Python and C++. Every block in C++ comes with a creating function, called gr_make_*** (gr_make_sig_source_f() in the example mentioned above). This function is always documented on the same page as the matching class, and this function is what gets exported to Python, so gr.sig_source_f() in Python calls gr_make_sig_source_f() in C++. For the same reason, it takes the same arguments - that's how you know how to initialise a block in Python. Once you're browsing the Doxygen documentation of the class gr_sig_source_f, you might notice many other class methods, such as set_frequency(). These functions get exported to Python as well. So if you have created a signal source and want to change the frequency (say your application has a user frequency control) you can use this method on your Python defined block:

1 2 3 4 5 6

# We're in some cool application here src0 = gr.sig_source_f (sample_rate, gr.GR_SIN_WAVE, 350, ampl) # Other, fantastic things happen here src0.set_frequency(880) # Change frequency

will change the frequency of the first signal generator to 880Hz. Hopefully, GNU Radio documentation will grow and become more and more complete. But to completely understand the workings of blocks in detail, you will probably have to have a look at the code sooner or later, no matter how good the documentation gets. Connecting blocks Use the connect() method of gr.top_block to connect blocks. Some things are worth mentioning:

You can only connect inputs and outputs if the data types match. If you try to connect a float output with a complex input, you will get an error. One output can be connected to several inputs; you don't need an extra block to duplicate signal paths.

These are basic rules for connecting blocks and they work in most cases. However, when mixing data types some more notes are worth mentioning.

GNU Radio checks if input and output types match by checking their size. If you happen to connect up ports with different types but the same size, you will most definitely get data junk. When processing single bits, be careful. In some cases, you will work with binary data in a usual sense, in other cases you want to handle a specific number of bits at a time. Have a look at the packed_to_unpacked* and unpacked_to_packed* blocks for this. Be careful with dynamic ranges. When you're using float or complex data types, you have a larger range than you'll ever need concerning the machine, but some sinks and sources have specific ranges you need to stick to. For example, audio sinks require samples within +-1 and will clip anything outside this interval. The USRP sink on the other hand needs samples in the +-32767 range (signed 16 bit values) because that's the dynamic range of the DAC.

Hierarchical blocks Sometimes it makes sense to combine several blocks into a new block. Say you have several applications which all have a common signal processing component which consists of several blocks. These blocks can be combined into a new block, which in turn can be used in your applications is if it were a normal GNU Radio block.

Example: Say you have two different flow graphs, FG1 and FG2. Both use - among others - the blocks B1 and B2. You want to combine them to a hierarchical block called HierBlock:
+-------------------+ | +-----+ +----+ | --+--+ B1 +--+ B2 +--+--| +-----+ +----+ | | [[HierBlock]] | +-------------------+

This is what you do: create a flow graph which derives from gr.hier_block2 and use self as source and sink: 1 class [[HierBlock]](gr.hier_block2): 2 def __init__(self, audio_rate, if_rate): 3 gr.hier_block2.__init__(self, "HierBlock", 4 gr.io_signature(1, 1, gr.sizeof_float), 5 gr.io_signature(1, 2, gr.sizeof_gr_complex)) 6 7 B1 = gr.block1(...) # Put in proper code here! 8 B2 = gr.block2(...) 9 10 self.connect(self, B1, B2, self) As you can see, creating a hierarchical block is very similar to creating a flow graph with gr.top_block. Apart from using self as source and sink, there is another difference: the constructor for the parent class (called in line 3) needs to receive additional information. The call to gr.hier_block2.+init+() takes four parameters:

self (which is always passed to the constructor as first argument), a string with an identifier for the hierarchical block (change at your convenience), an input signature and an output signature.

The last two require some extra explanation unless you have already written your own blocks in C++. GNU Radio needs to know what types of input and output the block uses. Creating an input/output signature can be done by calling gr.io_signature(), as is done here. This function call takes 3 arguments:

minimum number of ports, maximum number of ports and size of the input/output elements.

For the hierarchical block HierBlock, you can see that it has exactly one input and one or two outputs. The incoming objects are of size float, so the block processes incoming real float values. Somewhere in B1 or B2, the data is converted to complex float values, so the output signature declares outgoing objects to be of size gr.sizeof_gr_complex. The 'gr.sizeof_float@ and

gr.sizeof_gr_complex are equivalent to the C++ return values of the sizeof() call. Other predefined constants are

gr.sizeof_int gr.sizeof_short gr.sizeof_char

Use gr.io_signature(0, 0, 0) to create a null IO signature, i.e. for defining hierarchical blocks as sources or sinks. That's all. You can now use HierBlock as you would use a regular block. For example, you could put this code in the same file: 1 class FG1(gr.top_block): 2 def __init__(self): 3 gr.top_block.__init__(self) 4 5 ... # Sources and other blocks are defined here 6 other_block1 = gr.other_block() 7 hierblock = [[HierBlock]]() 8 other_block2 = gr.other_block() 9 10 self.connect(other_block1, hierblock, other_block2) 11 12 ... # Define rest of FG1 Of course, to make use of Pythons modularity, you could also put the code for HierBlock in an extra file called hier_block.py. To use this block from another file, simply add an import directive to your code: 1 from hier_block import [[HierBlock]] and you can use HierBlock as mentioned above. Examples for hierarchical blocks: gnuradio-examples/python/usrp/fm_tx4.py gnuradio-examples/python/usrp/fm_tx_2_daughterboards.py gnuradio-examples/python/digital/tx_voice.py Multiple flow graphs In some cases, you might want to have completely separate flow graphs, e.g. for receive and transmit paths (see the example 'Walkie-Talkie' above). Currently (June 2008), it is not possible to have multiple top_blocks running at the same time, but what you can do is create full flow graphs as hierarchical blocks using gr.hier_block2 like in the section above. Then, create a top_block to hold the flow graphs.

Example: 1 class transmit_path(gr.hier_block2): 2 def __init__(self): 3 gr.hier_block2.__init__(self, "transmit_path", 4 gr.io_signature(0, 0, 0), # Null signature 5 gr.io_signature(0, 0, 0)) 6 7 source_block = gr.source() 8 signal_proc = gr.other_block() 9 sink_block = gr.sink() 10 11 self.connect(source_block, signal_proc, sink_block) 12 13 class receive_path(gr.hier_block2): 14 def __init__(self): 15 gr.hier_block2.__init__(self, "receive_path", 16 gr.io_signature(0, 0, 0), # Null signature 17 gr.io_signature(0, 0, 0)) 18 19 source_block = gr.source() 20 signal_proc = gr.other_block() 21 sink_block = gr.sink() 22 23 self.connect(source_block, signal_proc, sink_block) 24 25 class my_top_block(gr.top_block): 26 def __init__(self): 27 gr.top_block.__init__(self) 28 29 tx_path = transmit_path() 30 31 rx_path = receive_path() 32 33 self.connect(tx_path) 34 self.connect(rx_path) Now, when you start my_top_block, both flow graphs are started in parallel. Note that the hierarchical blocks have explicitly no inputs and outputs defined, they have a null IO signature. Consequently, they don't connect to self as source or sink; they rather define their own sources or sink (just as you would do when defining a hierarchical block as source or sink). The top block simply connects the hierarchical blocks to itself, but does not connect them up in any way. Examples for multiple flow graphs: gnuradio-examples/python/usrp/usrp_nbfm_ptt.py

GNU Radio extensions and tools GNU Radio is more than blocks and flow graphs - it comes with a lot of tools and code to help you write DSP applications. A collection of useful GNU Radio applications designed to aid you is in gr-utils/. Browse the source code in gnuradio-core/src/python/gnuradio to find utilities you can use in your Python code such as filter design code, modulation utilities and more. Controlling flow graphs If you have followed the tutorial so far, you will have noticed that a flow graph has always been implemented as a class, derived from gr.top_block. The question remains on how to control one of these classes. As mentioned before, deriving the class from gr.top_block brings along all the functionality you might need. To run or stop an existing flow graph, use the following methods: The simplest way to run a flow graph. Calls start(), then wait(). Used to run a flow graph that will stop on its own, or to run a flow graph indefinitely until SIGINT is received. Start the contained flow graph. Returns to the caller once the threads are created. Stop the running flow graph. Notifies each thread created by the scheduler to shutdown, then returns to caller. Wait for a flow graph to complete. Flowgraphs complete when either (1) all blocks indicate that they are done, or (2) after stop has been called to request shutdown. Lock a flow graph in preparation for reconfiguration.

run()

start() stop()

wait() lock()

Unlock a flow graph in preparation for reconfiguration. When an equal number of unlock() calls to lock() and unlock() have occurred, the flow graph will be restarted automatically.

See the documentation for gr_top_block for more details.

Example: 1 class my_top_block(gr.top_block): 2 def __init__(self): 3 gr.top_block.__init__(self) 4 ... # Define blocks etc. here 5 6 if __name__ == '__main__': 7 my_top_block().start() 8 sleep(5) # Wait 5 secs (assuming sleep was imported!) 9 my_top_block().stop() 10 my_top_block().wait() # If the graph is needed to run again, wait() must be called after stop 11 ... # Reconfigure the graph or modify it 12 my_top_block().start() # start it again 13 sleep(5) # Wait 5 secs (assuming sleep was imported!) 14 my_top_block().stop() # since (assuming) the graph will not run again, no need for wait() to be called These methods help you to control the flow graph from the outside. For many problems this might not be enough: you don't simply want to start or stop a flow graph, you want to reconfigure the way it behaves. For example, imagine your application has a volume control somewhere in your flow graph. This volume control is implemented by inserting a multiplier into the sample stream. This multiplier is of type gr.multiply_const_ff. If you check the documentation for this kind of of block, you will find a function gr.multiply_const_ff.set_k() which sets the multiplication factor.

You need to make the settings visible to the outside in order to control it. The simplest way is to make the block an attribute of the flow graph class. Example: 1 class my_top_block(gr.top_block): 2 def __init__(self): 3 gr.top_block.__init__(self) 4 ... # Define some blocks 5 self.amp = gr.multiply_const_ff(1) # Define multiplier block 6 ... # Define more blocks 7 8 self.connect(..., self.amp, ...) # Connect all blocks 9 10 def set_volume(self, volume): 11 self.amp.set_k(volume) 12 13 if __name__ == '__main__': 14 my_top_block().start() 15 sleep(2) # Wait 2 secs (assuming sleep was imported!) 16 my_top_block.set_volume(2) # Pump up the volume (by factor 2) 17 sleep(2) # Wait 2 secs (assuming sleep was imported!) 18 my_top_block().stop() This example runs the flow graph for 2 seconds and then doubles the volume by accessing the amp block through a member function called set_volume(). Of course, one could have accessed the amp attribute directly, omitting the member function. Hint: making blocks attributes of the flow graph is generally a good idea as it makes extending the flow graph with extra member functions easier.

Non-flow graph centred applications Up until now, GNU Radio applications in this tutorial have always been centred around the one class derived from gr.top_block. However, this is not necessarily how GNU Radio needs to be used. GNU Radio was designed to develop DSP applications from Python, so there's no reason to not use the full power of Python when using GNU Radio. Python is an extremely powerful language, and new libraries and functionalities are constantly being added. In a way, GNU Radio extends Python with a powerful, real-time-capable DSP library. By combining this with other libraries you have immense functionality right there at your fingertips. For example, by combining GNU Radio with SciPy, a collection of scientific Python libraries, you can record RF signals in real time and do extensive mathematical operations off line, save statistics to a database and so on - all in the same application. Even expensive

engineering software such as Matlab might become unnecessary if you combine all these libraries. http://www.scipy.org/ Advanced Topics If you have really read the previous sections, you already know enough to write your first Python GNU Radio applications. This section will adress some slightly more advanced functionalities for Python GNU Radio applications. Dynamic flow graph creation For most cases, the aforementioned way to define flow graphs is completely adequate. If you need more flexibility in your application, you might want to have even more control over the flow graph from outside the class. This can be achieved by taking the code out of the +init+() function and simply using gr.top_block as a container. Example: 1 2 3 4 5 6 7 8 9 10 11 12 13 ... # We are inside some application tb = gr.top_block() # Define the container block1 = gr.some_other_block() block2 = gr.yet_another_block() tb.connect(block1, block2) ... # The application does some wonderful things here tb.start() # Start the flow graph ... # Do some more incredible and fascinating stuff here

If you are writing some application which needs to dynamically stop a flow graph (reconfigure it, re-start it and so) on this might be a more practical way to do it. Examples for this kind of flow graph setup: gnuradio-examples/python/apps/hf_explorer/hfx2.py Command Line Options Python has its own libraries to parse command line options. See the documentation for the module optparse to find out how to use it. GNU Radio extends optparse by new command line option types. Use @from gnuradio.eng_option import eng_option' to import this extension. With eng_option, you have the following types:

eng_float Like the original float option, but also accepts engineering notation like 101.8M subdev intx Only accepts valid subdevice descriptors such as A:0 (To specify a daughterboard on a USRP) Only accepts integers

If your application supports command line options, it would be ever so nice if you could stick to the GNU Radio conventions for command line options. You can find these (along with more hints for developers) in README.hacking. Nearly every GNU Radio example uses this feature. Try dial_tone.py for an easy example.

Graphical User Interfaces If you are a Python expert and also have some experience in writing GUIs for Python (using whatever GUI toolkit you like), you might not even need this section. As mentioned before, GNU Radio merely extends Python with DSP routines - so if you like, just go ahead and write a GUI application, add a GNU Radio flow graph to it and define some interfaces to carry GNU Radio information to your application and vice versa. If you want to plot your data, you could use Matplotlib or Qwt. However, sometimes you simply want to write a quick GUI application without bothering with setting up widgets, defining all the menus etc. GNU Radio comes with some predefined classes to help you write graphical GNU Radio applications. These modules are based on wxWidgets (or to be precise, wxPython), a platform-independent GUI toolkit. You will need some background in wxPython - but don't worry, it is not that complicated and there are several tutorials available on the net. Check the wxPython website for documentation (http://www.wxpython.org/). To use the GNU Radio wxWidgets tools, you need to import some modules: 1 from gnuradio.wxgui import stdgui2, fftsink2, slider, form Here, 4 components were imported from the gnuradio.wxgui submodule. Here's a quick list of the modules (again, not necessarily complete. You will have to browse the modules or the source code in gr-wxgui/src/python).

stdgui2 fftsink2 scopesink2

Basic GUI stuff, you always need this Plot FFTs of your data to create spectrum analyzers or whatever Oscilloscope output

waterfallsink2 Waterfall output numbersink2 form Displays numerical values of incoming data Often used input forms (see below)

Next, we have to define a new flow graph. This time, we don't derive from gr.top_block but from stdgui2.std_top_block: 1 class my_gui_flow graph(stdgui2.std_top_block): 2 def __init__(self, frame, panel, vbox, argv): 3 stdgui2.std_top_block.__init__ (self, frame, panel, vbox, argv) As you can see, there's another difference: the constructor gets a couple of new parameters. This is because a stdgui2.std_top_block does not only include flow graph functionality (it is derived from gr.top_block itself), but also directly creates a window with some basic components (like a menu). This is good news for all of those who just want to quickly hack a graphical application: GNU Radio creates the window and everything, you just need to add the widgets. Here's a list of what you can do with these new objects (this probably won't mean much to you if you have no idea about GUI programming): frame The wx.Frame of your window. You can get at the predefined menu by using frame.GetMenuBar()

panel A panel, placed in @frame', to hold all your wxControl widgets vbox argv A vertical box sizer (wx.BoxSizer(wx.VERTICAL) is how it is defined), used to align your widgets in the panel The command line arguments

Now you have all you need to create your GUI. You can simply add new box sizers and widgets to vbox, change the menu or whatever. Some typical functions have been simplified further in the GNU Radio GUI library form.

form has a great number of input widgets: form.static_text_field() for static text field (display only), form.float_field(), to input float values, form.text_field() to input text, form.checkbox_field() for checkboxes, form.radiobox_field() for radioboxes etc. Check the source code of gr-wxgui/src/python/form.py for the complete list. Most of these calls pass most of their arguments to the appropriate wxPython objects, so the function arguments are quite selfexplanatory. See one of the examples mentioned below on how to add widgets using form. Probably the most useful part of gnuradio.wxgui is the possibility to directly plot incoming data. To do this, you need one of the sinks that come with gnuradio.wxgui, such as fftsink2. These sinks work just as any other GNU Radio sink, but also have properties needed for use with wxPython. Example: 1 from gnuradio.wxgui import stdgui2, fftsink2 2 3 # App gets defined here ... 4 5 # FFT display (pseudo-spectrum analyzer) 6 my_fft = fftsink2.fft_sink_f(panel, title="FFT of some Signal", fft_size=512, 7 sample_rate=sample_rate, ref_level=0, y_per_div=20) 8 self.connect(source_block, my_fft) 9 vbox.Add(my_fft.win, 1, wx.EXPAND) First, the block is defined (fftsink2.fft_sink_f). Apart from typical DSP parameters such as the sampling rate, it also needs the panel object which is passed to the constructor. Next, the block is connected to a source. Finally, the FFT window (my_fft.win) is placed inside the vbox BoxSizer to actually display it. Remember that a signal block output can be connected to any amount of inputs. Finally, the whole thing needs to be started. Because we need an wx.App() to run the GUI, the startup code is a bit different from a regular flow graph: 1 if __name__ == '__main__': 2 app = stdgui2.stdapp(my_gui_flow_graph, "GUI GNU Radio Application") 3 app.MainLoop() stdgui2.stdapp() creates the wx.App with my_gui_flow_graph (the first argument). The window title is set to "GUI GNU Radio Application". Examples for simple GNU Radio GUIs: gr-utils/src/python/usrp_fft.py gr-utils/src/python/usrp_oscope.py gnuradio-examples/python/audio/audio_fft.py gnuradio-examples/python/usrp/usrp_am_mw_rcv.py And many more.

The C++ domain: Extending GNU Radio GNU Radio is extremely powerful and includes many kinds of signal processing blocks. However, if you're developing something particular, chances are high that sooner or later you'll be running into some component which is lacking; be it a specific channel code, a segmentation algorithm or whatever. In this case, you will want to write your own blocks to add them into GNU Radio. This is usually done in C++, in order to keep GNU Radio as fast as it is. If this is what you need, check out the tutorial on how to write a new block.

How to Write a Signal Processing Block

Prerequisites Introduction The View from 30,000 Feet Autotools, Makefiles, and Directory Layout Naming Conventions Death to CamelCaseNames! Global Names Package Prefixes Class Data Members (instance variables) Class Static Data Members (class variables) File Names Suffixes First Block: howto_square_ff Test Driven Programming Build Tree vs. Install Tree make check

The C++ code The SWIG .i file Putting it all together Additional gr_block methods forecast set_output_multiple Subclasses for common patterns gr_sync_block gr_sync_decimator gr_sync_interpolator Second Block: howto_square2_ff Where to from Here? Miscellaneous Tips Sources and Sinks Debugging with gdb Performance Measurement with oprofile Coming Attractions Improved Type System Hierarchical Blocks Prerequisites We assume that the reader has basic familiarity with GNU Radio and has read and understood Exploring GNU Radio : http://www.gnu.org/software/gnuradio/doc/exploring-gnuradio.html There is a tarball of files that accompany this article. It includes the examples, DocBook source for the article and all the Makefiles etc it takes to make it work. Grab it at ftp://ftp.gnu.org/gnu/gnuradio or one of the mirrors. The file you want is gr-howto-write-a-blockX.Y.tar.gz. Pick the one with the highest version number. See http://comsec.com/wiki?CvsAccess for CVS Access.

Introduction GNU Radio provides a framework for building software radios. Waveforms -- signal processing applications -- are built using a combination of Python code for high level organization, policy, GUI and other non performance-critical functions, while performance critical signal processing blocks are written in C++. From the Python point of view, GNU Radio provides a data flow abstraction. The fundamental concepts are signal processing blocks and the connections between them. This abstraction is implemented by the Python gr.flow_graph class. Each block has a set of input ports and output ports. Each port has an associated data type. The most common port types are float and gr_complex (equivalent to std::complex<float>), though other types are used, including those representing structures, arrays or other types of packetized data. From the high level point-of-view, infinite streams of data flow through the ports. At the C++ level, streams are dealt with in convenient sized pieces, represented as contiguous arrays of the underlying type. The View from 30,000 Feet This article will walk through the construction of several simple signal processing blocks, and explain the techniques and idioms used. Later sections cover debugging signal processing blocks in the mixed Python/C++ environment and performance measurement and optimization. The example blocks will be built in the style of all GNU Radio extensions. That is, they are built outside of the gnuradio-core build tree, and are constructed as shared libraries that may be dynamically loaded into Python using the "import" mechanism. SWIG, the Simplified Wrapper and Interface Generator, is used to generate the glue that allows our code to be used from Python. The C++ class gr_block is the base of all signal processing blocks in GNU Radio. Writing a new signal processing block involves creating 3 files: The .h and .cc files that define the new class and the .i file that tells SWIG how to generate the glue that binds the class into Python. The new class must derive from gr_block or one of it's subclasses. Our first examples will derive directly from gr_block. Later we will look at some other subclasses that simplify the process for common cases.

Autotools, Makefiles, and Directory Layout Before we dive into the code, let's talk a bit about the overall build environment and the directory structure that we'll be using. To reduce the amount of Makefile hacking that we have to do, and to facilitate portability across a variety of systems, we use the GNU autoconf, automake, and libtool tools. These are collectively referred to as the autotools, and once you get over the initial shock, they will become your friends. (The good news is that we provide boilerplate that can be used pretty much as-is.) automake automake and configure work together to generate GNU compliant Makefiles from a much higher level description contained in the corresponding Makefile.am file. Makefile.am specifies the libraries and programs to build and the source files that compose each. Automake reads Makefile.am and produces Makefile.in. Configure reads Makefile.in and produces Makefile. The resulting Makefile contains a zillion rules that do the right right thing to build, check and install your code. It is not uncommon for the the resulting Makefile to be 5 or 6 times larger than Makefile.am. autoconf autoconf reads configure.ac and produces the configure shell script. configure automatically tests for features of the underlying system and sets a bunch of variables and defines that can be used in the Makefiles and your C++ code to conditionalize the build. If features are required but not found, configure will output an error message and stop. libtool libtool works behind the scenes and provides the magic to construct shared libraries on a wide variety of systems. Table below, Directory Layout shows the directory layout and common files we'll be using. After renaming the topdir directory, use it in your projects too. We'll talk about particular files as they come up later.

Table . Directory Layout File/Dir Name topdir/Makefile.am topdir/Makefile.common topdir/bootstrap topdir/config topdir/configure.ac topdir/src topdir/src/lib topdir/src/lib/Makefile.am topdir/src/python topdir/src/python/Makefile.am topdir/src/python/run_tests Naming Conventions GNU Radio uses a set of naming conventions to assist in comprehending the code base and gluing C++ and Python together. Please follow them. Death to CamelCaseNames! We've returned to a kinder, gentler era. We're now using the "STL style" naming convention with a couple of modifications since we're not using namespaces. With the exception of macros and other constant values, all identifiers shall be lower case with words_separated_like_this. Macros and constant values (e.g., enumerated values, static const int FOO = 23) shall be in UPPER_CASE. Script to run tests in the build tree Python code goes here C++ code goes here Comment Top level Makefile.am Common fragment included in sub-Makefiles Runs autoconf, automake, libtool first time through Directory of m4 macros used by configure.ac Input to autoconf

Global Names All globally visible names (types, functions, variables, consts, etc) shall begin with a "package prefix", followed by an underscore. The bulk of the code in GNU Radio belongs to the "gr" package, hence names look like gr_open_file (...). Large coherent bodies of code may use other package prefixes, but let's try to keep them to a well thought out list. See the list below.

Package Prefixes These are the current package prefixes: gr_ Almost everything. gri_ Implementation primitives. Sometimes we have both a gr_foo and a gri_foo. In that case, gr_foo would be derived from gr_block and gri_foo would be the low level guts of the function. atsc_ Code related to the Advanced Television Standards Committee HDTV implementation usrp_ Universal Software Radio Peripheral. qa_ Quality Assurance (Test code.)

Class Data Members (instance variables) All class data members shall begin with d_foo. The big win is when you're staring at a block of code it's obvious which of the things being assigned to persist outside of the block. This also keeps you from having to be creative with parameter names for methods and constructors. You just use the same name as the instance variable, without the d_.

class gr_wonderfulness { std::string d_name; double d_wonderfulness_factor; public: gr_wonderfulness (std::string name, double wonderfulness_factor) : d_name (name), d_wonderfulness_factor (wonderfulness_factor) { ... } ... }; Class Static Data Members (class variables) All class static data members shall begin with s_foo. File Names Each significant class shall be contained in its own file. The declaration of class gr_foo shall be in gr_foo.h and the definition in gr_foo.cc. Suffixes By convention, we encode the input and output types of signal processing blocks in their name using suffixes. The suffix is typically one or two characters long. Source and sinks have single character suffixes. Regular blocks that have both inputs and outputs have two character suffixes. The first character indicates the type of the input streams, the second indicates the type of the output streams. FIR filter blocks have a three character suffix, indicating the type of the inputs, outputs and taps, respectively. These are the suffix characters and their interpretations:

f - single precision floating point c - complex<float> s - short (16-bit integer) i - integer (32-bit integer)

In addition, for those cases where the block deals with streams of vectors, we use the character 'v' as the first character of the suffix. An example of this usage is gr_fft_vcc. The FFT block takes a vector of complex numbers on its input and produces a vector of complex numbers on its output. First Block: howto_square_ff For our first example we'll create a block that computes the square of its single float input. This block will accept a single float input stream and produce a single float output stream.

Following the naming conventions, we'll use howto as our package prefix, and the block will be called howto_square_ff. We are going to arrange that this block, as well as the others that we write in this article, end up in the gnuradio.howto Python module. This will allow us to access it from Python like this: from gnuradio import howto sqr = howto.square_ff () Test Driven Programming We could just start banging out the C++ code, but being highly evolved modern programmers, we're going to write the test code first. After all, we do have a good spec for the behavior: take a single stream of floats as the input and produce a single stream of floats as the output. The output should be the square of the input. How hard could this be? Turns out that this is easy! Check out Example 1, qa_howto.py (first version). Example 1. qa_howto.py (first version) 1 #!/usr/bin/env python 2 3 from gnuradio import gr, gr_unittest 4 import howto 5 6 class qa_howto (gr_unittest.TestCase): 7 8 def setUp (self): 9 self.fg = gr.flow_graph () 10 11 def tearDown (self): 12 self.fg = None 13 14 def test_001_square_ff (self): 15 src_data = (-3, 4, -5.5, 2, 3) 16 expected_result = (9, 16, 30.25, 4, 9) 17 src = gr.vector_source_f (src_data) 18 sqr = howto.square_ff () 19 dst = gr.vector_sink_f () 20 self.fg.connect (src, sqr) 21 self.fg.connect (sqr, dst) 22 self.fg.run () 23 result_data = dst.data () 24 self.assertFloatTuplesAlmostEqual (expected_result, result_data, 6) 25 26 if __name__ == '__main__': 27 gr_unittest.main ()

gr_unittest is an extension to the standard python module unittest. gr_unittest adds support for checking approximate equality of tuples of float and complex numbers. Unittest uses Python's reflection mechanism to find all methods that start with test_ and runs them. Unittest wraps each call to test_* with matching calls to setUp and tearDown. See the python unittest documentation for details. http://docs.python.org/lib/module-unittest.html When we run the test, gr_unittest.main is going to invoke setUp, test_001_square_ff, and tearDown. test_001_square_ff builds a small graph that contains three nodes. gr.vector_source_f(src_data) will source the elements of src_data and then say that it's finished. howto.square_ff is the block we're testing. gr.vector_sink_f gathers the output of howto.square_ff. The run method runs the graph until all the blocks indicate they are finished. Finally, we check that the result of executing square_ff on src_data matches what we expect.

Build Tree vs. Install Tree The build tree is everything from topdir (the one containing configure.ac) down. The path to the install tree is prefix/lib/pythonversion/site-packages, where prefix is the --prefix argument to configure (default /usr/local) and version is the installed version of python. A typical value is /usr/local/lib/python2.3/site-packages. We normally set our PYTHONPATH environment variable to point at the install tree, and do this in ~/.bash_profile or ~/.profile. This allows our python apps to access all the standard python libraries, plus our locally installed stuff like GNU Radio. We write our applications such that they access the code and libraries in the install tree. On the other hand, we want our test code to run on the build tree, where we can detect problems before installation.

make check We use make check to run our tests. Make check invokes the run_tests shell script which sets up the PYTHONPATH environment variable so that our tests use the build tree versions of our code and libraries. It then runs all files which have names of the form qa_*.py and reports the overall success or failure. There is quite a bit of behind-the-scenes action required to use the non-installed versions of our code (look at runtest for a cheap thrill.) Finally, running make check in the python directory produces this result: [eb@bufo python]$ make check make check-TESTS make[1]: Entering directory `/home/eb/gr-build/gr-howto-write-a-block/src/python' Traceback (most recent call last): File "./qa_howto.py", line 24, in ? import howto ImportError: No module named howto Traceback (most recent call last): File "./qa_howto_1.py", line 24, in ? import howto ImportError: No module named howto FAIL: run_tests =================== 1 of 1 tests failed =================== make[1]: *** [check-TESTS] Error 1 make[1]: Leaving directory `/home/eb/gr-build/gr-howto-write-a-block/src/python' make: *** [check-am] Error 2 [eb@bufo python]$ Excellent! Our test failed, just as we expected. The ImportError indicates that it can't find the module named howto. No surprise, since we haven't written it yet.

The C++ code Now that we've got a test case written that successfully fails, let's write the C++ code. As we mentioned earlier, all signal processing blocks are derived from gr_block or one of its subclasses. Let's take a look at Example 2, gr_block.h.

Example 2. gr_block.h 1 /* -*- c++ -*- */ 2 /* 3 * Copyright 2004 Free Software Foundation, Inc. 4 * 5 * This file is part of GNU Radio 6 * 7 * GNU Radio is free software; you can redistribute it and/or modify 8 * it under the terms of the GNU General Public License as published by 9 * the Free Software Foundation; either version 2, or (at your option) 10 * any later version. 11 * 12 * GNU Radio is distributed in the hope that it will be useful, 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 * GNU General Public License for more details. 16 * 17 * You should have received a copy of the GNU General Public License 18 * along with GNU Radio; see the file COPYING. If not, write to 19 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, 20 * Boston, MA 02111-1307, USA. 21 */ 22 23 #ifndef INCLUDED_GR_BLOCK_H 24 #define INCLUDED_GR_BLOCK_H 25 26 #include <gr_runtime.h> 27 #include <string> 28 29 /*! 30 * \brief The abstract base class for all signal processing blocks. 31 * \ingroup block 32 * 33 * Blocks have a set of input streams and output streams. The 34 * input_signature and output_signature define the number of input 35 * streams and output streams respectively, and the type of the data 36 * items in each stream. 37 * 38 * Although blocks may consume data on each input stream at a 39 * different rate, all outputs streams must produce data at the same 40 * rate. That rate may be different from any of the input rates. 41 * 42 * User derived blocks override two methods, forecast and general_work, 43 * to implement their signal processing behavior. forecast is called 44 * by the system scheduler to determine how many items are required on

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

* each input stream in order to produce a given number of output * items. * * general_work is called to perform the signal processing in the block. * It reads the input items and writes the output items. */ class gr_block { public: virtual ~gr_block (); std::string name () const { return d_name; } gr_io_signature_sptr input_signature () const { return d_input_signature; } gr_io_signature_sptr output_signature () const { return d_output_signature; } long unique_id () const { return d_unique_id; } /*! * Assume block computes y_i = f(x_i, x_i-1, x_i-2, x_i-3...) * History is the number of x_i's that are examined to produce one y_i. * This comes in handy for FIR filters, where we use history to * ensure that our input contains the appropriate "history" for the * filter. History should be equal to the number of filter taps. */ unsigned history () const { return d_history; } void set_history (unsigned history) { d_history = history; } /*! * \brief return true if this block has a fixed input to output rate * * If true, then fixed_rate_in_to_out and fixed_rate_out_to_in may be called. */ bool fixed_rate() const { return d_fixed_rate; } // ---------------------------------------------------------------// override these to define your behavior // ---------------------------------------------------------------/*! * \brief Estimate input requirements given output request * * \param noutput_items number of output items to produce * \param ninput_items_required number of input items required on each input stream * * Given a request to product \p noutput_items, estimate the number of

91 * data items required on each input stream. The estimate doesn't have 92 * to be exact, but should be close. 93 */ 94 virtual void forecast (int noutput_items, 95 gr_vector_int &ninput_items_required); 96 97 /*! 98 * \brief compute output items from input items 99 * 100 * \param noutput_items number of output items to write on each output stream 101 * \param ninput_items number of input items available on each input stream 102 * \param input_items vector of pointers to the input items, one entry per input stream 103 * \param output_items vector of pointers to the output items, one entry per output stream 104 * 105 * \returns number of items actually written to each output stream, or -1 on EOF. 106 * It is OK to return a value less than noutput_items. -1 <= return value <= noutput_items 107 * 108 * general_work must call consume or consume_each to indicate how many items 109 * were consumed on each input stream. 110 */ 111 virtual int general_work (int noutput_items, 112 gr_vector_int &ninput_items, 113 gr_vector_const_void_star &input_items, 114 gr_vector_void_star &output_items) = 0; 115 116 /*! 117 * \brief Confirm that ninputs and noutputs is an acceptable combination. 118 * 119 * \param ninputs number of input streams connected 120 * \param noutputs number of output streams connected 121 * 122 * \returns true if this is a valid configuration for this block. 123 * 124 * This function is called by the runtime system whenever the 125 * topology changes. Most classes do not need to override this. 126 * This check is in addition to the constraints specified by the input 127 * and output gr_io_signatures. 128 */ 129 virtual bool check_topology (int ninputs, int noutputs); 130 131 /*! 132 * \brief Called to enable drivers, etc for i/o devices. 133 * 134 * This allows a block to enable an associated driver to begin 135 * transfering data just before we start to execute the scheduler.

136 * The end result is that this reduces latency in the pipeline when 137 * dealing with audio devices, usrps, etc. 138 */ 139 virtual bool start(); 140 141 /*! 142 * \brief Called to disable drivers, etc for i/o devices. 143 */ 144 virtual bool stop(); 145 146 // ---------------------------------------------------------------147 148 /*! 149 * \brief Constrain the noutput_items argument passed to forecast and general_work 150 * 151 * set_output_multiple causes the scheduler to ensure that the noutput_items 152 * argument passed to forecast and general_work will be an integer multiple 153 * of \param multiple The default value of output multiple is 1. 154 */ 155 void set_output_multiple (int multiple); 156 int output_multiple () const { return d_output_multiple; } 157 158 /*! 159 * \brief Tell the scheduler \p how_many_items of input stream \p which_input were consumed. 160 */ 161 void consume (int which_input, int how_many_items); 162 163 /*! 164 * \brief Tell the scheduler \p how_many_items were consumed on each input stream. 165 */ 166 void consume_each (int how_many_items); 167 168 /*! 169 * \brief Set the approximate output rate / input rate 170 * 171 * Provide a hint to the buffer allocator and scheduler. 172 * The default relative_rate is 1.0 173 * 174 * decimators have relative_rates < 1.0 175 * interpolators have relative_rates > 1.0 176 */ 177 void set_relative_rate (double relative_rate); 178 179 /*! 180 * \brief return the approximate output rate / input rate

181 */ 182 double relative_rate () const { return d_relative_rate; } 183 184 /* 185 * The following two methods provide special case info to the 186 * scheduler in the event that a block has a fixed input to output 187 * ratio. gr_sync_block, gr_sync_decimator and gr_sync_interpolator 188 * override these. If you're fixed rate, subclass one of those. 189 */ 190 /*! 191 * \brief Given ninput samples, return number of output samples that will be produced. 192 * N.B. this is only defined if fixed_rate returns true. 193 * Generally speaking, you don't need to override this. 194 */ 195 virtual int fixed_rate_ninput_to_noutput(int ninput); 196 197 /*! 198 * \brief Given noutput samples, return number of input samples required to produce noutput. 199 * N.B. this is only defined if fixed_rate returns true. 200 * Generally speaking, you don't need to override this. 201 */ 202 virtual int fixed_rate_noutput_to_ninput(int noutput); 203 204 // ---------------------------------------------------------------------------205 206 private: 207 208 std::string d_name; 209 gr_io_signature_sptr d_input_signature; 210 gr_io_signature_sptr d_output_signature; 211 int d_output_multiple; 212 double d_relative_rate; // approx output_rate / input_rate 213 gr_block_detail_sptr d_detail; // implementation details 214 long d_unique_id; // convenient for debugging 215 unsigned d_history; 216 bool d_fixed_rate; 217 218 219 protected: 220 221 gr_block (const std::string &name, 222 gr_io_signature_sptr input_signature, 223 gr_io_signature_sptr output_signature); 224 225 //! may only be called during constructor

226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247

void set_input_signature (gr_io_signature_sptr iosig){ d_input_signature = iosig; } //! may only be called during constructor void set_output_signature (gr_io_signature_sptr iosig){ d_output_signature = iosig; } void set_fixed_rate(bool fixed_rate){ d_fixed_rate = fixed_rate; } // These are really only for internal use, but leaving them public avoids // having to work up an ever-varying list of friends public: gr_block_detail_sptr detail () const { return d_detail; } void set_detail (gr_block_detail_sptr detail) { d_detail = detail; } }; long gr_block_ncurrently_allocated (); #endif /* INCLUDED_GR_BLOCK_H */

A quick scan of gr_block.h reveals that since general_work is pure virtual, we definitely need to override that. general_work is the method that does the actual signal processing. For our squaring example we'll need to override general_work and provide a constructor and destructor and a bit of stuff to take advantage of the boost shared_ptrs.: http://www.boost.org/ http://www.boost.org/libs/smart_ptr/smart_ptr.htm Example 3, howto_square_ff.h and Example 4, howto_square_ff.cc are the header and c++ source.

Example 3. howto_square_ff.h 1 /* -*- c++ -*- */ 2 /* 3 * Copyright 2004 Free Software Foundation, Inc. 4 * 5 * This file is part of GNU Radio 6 * 7 * GNU Radio is free software; you can redistribute it and/or modify 8 * it under the terms of the GNU General Public License as published by 9 * the Free Software Foundation; either version 2, or (at your option) 10 * any later version. 11 * 12 * GNU Radio is distributed in the hope that it will be useful, 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 * GNU General Public License for more details. 16 * 17 * You should have received a copy of the GNU General Public License 18 * along with GNU Radio; see the file COPYING. If not, write to 19 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, 20 * Boston, MA 02111-1307, USA. 21 */ 22 #ifndef INCLUDED_HOWTO_SQUARE_FF_H 23 #define INCLUDED_HOWTO_SQUARE_FF_H 24 25 #include <gr_block.h> 26 27 class howto_square_ff; 28 29 /* 30 * We use boost::shared_ptr's instead of raw pointers for all access 31 * to gr_blocks (and many other data structures). The shared_ptr gets 32 * us transparent reference counting, which greatly simplifies storage 33 * management issues. This is especially helpful in our hybrid 34 * C++ / Python system. 35 * 36 * See http://www.boost.org/libs/smart_ptr/smart_ptr.htm 37 * 38 * As a convention, the _sptr suffix indicates a boost::shared_ptr 39 */ 40 typedef boost::shared_ptr<howto_square_ff> howto_square_ff_sptr; 41 42 /*! 43 * \brief Return a shared_ptr to a new instance of howto_square_ff. 44 *

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78

* To avoid accidental use of raw pointers, howto_square_ff's * constructor is private. howto_make_square_ff is the public * interface for creating new instances. */ howto_square_ff_sptr howto_make_square_ff (); /*! * \brief square a stream of floats. * \ingroup block * * \sa howto_square2_ff for a version that subclasses gr_sync_block. */ class howto_square_ff : public gr_block { private: // The friend declaration allows howto_make_square_ff to // access the private constructor. friend howto_square_ff_sptr howto_make_square_ff (); howto_square_ff (); // private constructor public: ~howto_square_ff (); // public destructor // Where all the action really happens int general_work (int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; #endif /* INCLUDED_HOWTO_SQUARE_FF_H */

Example 4. howto_square_ff.cc 1 /* -*- c++ -*- */ 2 /* 3 * Copyright 2004 Free Software Foundation, Inc. 4 * 5 * This file is part of GNU Radio 6 * 7 * GNU Radio is free software; you can redistribute it and/or modify 8 * it under the terms of the GNU General Public License as published by 9 * the Free Software Foundation; either version 2, or (at your option) 10 * any later version. 11 * 12 * GNU Radio is distributed in the hope that it will be useful, 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 * GNU General Public License for more details. 16 * 17 * You should have received a copy of the GNU General Public License 18 * along with GNU Radio; see the file COPYING. If not, write to 19 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, 20 * Boston, MA 02111-1307, USA. 21 */ 22 23 /* 24 * config.h is generated by configure. It contains the results 25 * of probing for features, options etc. It should be the first 26 * file included in your .cc file. 27 */ 28 #ifdef HAVE_CONFIG_H 29 #include "config.h" 30 #endif 31 32 #include <howto_square_ff.h> 33 #include <gr_io_signature.h> 34 35 /* 36 * Create a new instance of howto_square_ff and return 37 * a boost shared_ptr. This is effectively the public constructor. 38 */ 39 howto_square_ff_sptr 40 howto_make_square_ff () 41 { 42 return howto_square_ff_sptr (new howto_square_ff ()); 43 } 44

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

/* * Specify constraints on number of input and output streams. * This info is used to construct the input and output signatures * (2nd & 3rd args to gr_block's constructor). The input and * output signatures are used by the runtime system to * check that a valid number and type of inputs and outputs * are connected to this block. In this case, we accept * only 1 input and 1 output. */ static const int MIN_IN = 1; // mininum number of input streams static const int MAX_IN = 1; // maximum number of input streams static const int MIN_OUT = 1; // minimum number of output streams static const int MAX_OUT = 1; // maximum number of output streams /* * The private constructor */ howto_square_ff::howto_square_ff () : gr_block ("square_ff", gr_make_io_signature (MIN_IN, MAX_IN, sizeof (float)), gr_make_io_signature (MIN_OUT, MAX_OUT, sizeof (float))) { // nothing else required in this example } /* * Our virtual destructor. */ howto_square_ff::~howto_square_ff () { // nothing else required in this example } int howto_square_ff::general_work (int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float *) input_items[0]; float *out = (float *) output_items[0]; for (int i = 0; i < noutput_items; i++){ out[i] = in[i] * in[i]; }

91 92 93 94 95 96 97 98

// Tell runtime system how many input items we consumed on // each input stream. consume_each (noutput_items); // Tell runtime system how many output items we produced. return noutput_items; }

Now we need a Makefile.am to get all this to build. Example 5, src/lib/Makefile.am (no SWIG) is enough to build a shared library from our source file. We'll be adding additional rules to use SWIG in just a bit. If you haven't already, this is a good time to browse all the Makefile.am's in the build tree and get an idea for how it all hangs together. Example 5. src/lib/Makefile.am (no SWIG) 1 include $(top_srcdir)/Makefile.common 2 3 # Install this stuff so that it ends up as the gnuradio.howto module 4 # This usually ends up at: 5 # ${prefix}/lib/python${python_version}/site-packages/gnuradio 6 7 ourpythondir = $(grpythondir) 8 ourlibdir = $(grpyexecdir) 9 10 INCLUDES = $(STD_DEFINES_AND_INCLUDES) $(PYTHON_CPPFLAGS) 11 12 ourlib_LTLIBRARIES = _howto.la 13 14 # These are the source files that go into the shared library 15 _howto_la_SOURCES = \ 16 howto_square_ff.cc 17 18 # magic flags 19 _howto_la_LDFLAGS = -module -avoid-version 20 21 # These headers get installed in ${prefix}/include/gnuradio 22 grinclude_HEADERS = \ 23 howto_square_ff.h 24 25 MOSTLYCLEANFILES = $(BUILT_SOURCES) *.pyc

The SWIG .i file Now that we've got something that will compile, we need to write the SWIG .i file. This is a pared-down version of the .h file, plus a bit of magic that has python work with the boost shared_ptr's. To reduce code bloat, we only declare methods that we'll want to access from Python. We're going to call the .i file howto.i, and use it to hold the SWIG declarations for all classes from howto that will be accessible from python. It's quite small: 1 /* -*- c++ -*- */ 2 3 %include "exception.i" 4 %import "gnuradio.i" // the common stuff 5 6 %{ 7 #include "gnuradio_swig_bug_workaround.h" // mandatory bug fix 8 #include "howto_square_ff.h" 9 #include <stdexcept> 10 %} 11 12 // ---------------------------------------------------------------13 14 /* 15 * First arg is the package prefix. 16 * Second arg is the name of the class minus the prefix. 17 * 18 * This does some behind-the-scenes magic so we can 19 * access howto_square_ff from python as howto.square_ff 20 */ 21 GR_SWIG_BLOCK_MAGIC(howto,square_ff); 22 23 howto_square_ff_sptr howto_make_square_ff (); 24 25 class howto_square_ff : public gr_block 26 { 27 private: 28 howto_square_ff (); 29 };

Putting it all together Now we need to modify src/lib/Makefile.am to run SWIG and to add the glue it generates to the shared library. Example 6. src/lib/Makefile.am (with SWIG) 1 # 2 # Copyright 2004 Free Software Foundation, Inc. 3 # 4 # This file is part of GNU Radio 5 # 6 # GNU Radio is free software; you can redistribute it and/or modify 7 # it under the terms of the GNU General Public License as published by 8 # the Free Software Foundation; either version 2, or (at your option) 9 # any later version. 10 # 11 # GNU Radio is distributed in the hope that it will be useful, 12 # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 # GNU General Public License for more details. 15 # 16 # You should have received a copy of the GNU General Public License 17 # along with GNU Radio; see the file COPYING. If not, write to 18 # the Free Software Foundation, Inc., 59 Temple Place - Suite 330, 19 # Boston, MA 02111-1307, USA. 20 # 21 22 include $(top_srcdir)/Makefile.common 23 24 # Install this stuff so that it ends up as the gnuradio.howto module 25 # This usually ends up at: 26 # ${prefix}/lib/python${python_version}/site-packages/gnuradio 27 28 ourpythondir = $(grpythondir) 29 ourlibdir = $(grpyexecdir) 30 31 INCLUDES = $(STD_DEFINES_AND_INCLUDES) $(PYTHON_CPPFLAGS) 32 33 SWIGCPPPYTHONARGS = -noruntime -c++ -python $(PYTHON_CPPFLAGS) \ 34 -I$(swigincludedir) -I$(grincludedir) 35 36 ALL_IFILES = \ 37 $(LOCAL_IFILES) \ 38 $(NON_LOCAL_IFILES) 39

40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85

NON_LOCAL_IFILES = \ $(GNURADIO_CORE_INCLUDEDIR)/swig/gnuradio.i LOCAL_IFILES = howto.i \

# These files are built by SWIG. The first is the C++ glue. # The second is the python wrapper that loads the _howto shared library # and knows how to call our extensions. BUILT_SOURCES = howto.cc howto.py \ \

# This gets howto.py installed in the right place ourpython_PYTHON = \ howto.py ourlib_LTLIBRARIES = _howto.la # These are the source files that go into the shared library _howto_la_SOURCES = \ howto.cc \ howto_square_ff.cc # magic flags _howto_la_LDFLAGS = -module -avoid-version # link the library against some comon swig runtime code and the # c++ standard library _howto_la_LIBADD = \ -lgrswigrunpy \ -lstdc++ howto.cc howto.py: howto.i $(ALL_IFILES) $(SWIG) $(SWIGCPPPYTHONARGS) -module howto -o howto.cc $< # These headers get installed in ${prefix}/include/gnuradio grinclude_HEADERS = \ howto_square_ff.h # These swig headers get installed in ${prefix}/include/gnuradio/swig swiginclude_HEADERS = \ $(LOCAL_IFILES)

86 MOSTLYCLEANFILES = $(BUILT_SOURCES) *.pyc make now builds everything successfully. We get a few warnings, but that's OK. Changing directories back to the python directory we try make check again: [eb@bufo python]$ make check make check-TESTS make[1]: Entering directory `/home/eb/gr-build/gr-howto-write-a-block/src/python' . ---------------------------------------------------------------------Ran 1 test in 0.004s OK PASS: run_tests ================== All 1 tests passed ================== make[1]: Leaving directory `/home/eb/gr-build/gr-howto-write-a-block/src/python' [eb@bufo python]$ Victory! Our new block works!

Additional gr_block methods In our howto_square_ff example above, we only had to override the general_work method to accomplish our goal. gr_block provides a few other methods that are sometimes useful. forecast Looking at general_work you may have wondered how the system knows how much data it needs to ensure is valid in each of the input arrays. The forecast method provides this information. The default implementation of forecast says there is a 1:1 relationship between noutput_items and the requirements for each input stream. The size of the items is defined by gr_io_signatures in the constructor of gr_block. The sizes of the input and output items can of course differ; this still qualifies as a 1:1 relationship.

// default implementation: 1:1 void gr_block::forecast (int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size (); for (unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = noutput_items; } Although the 1:1 implementation worked for howto_square_ff, it wouldn't be appropriate for interpolators, decimators, or blocks with a more complicated relationship between noutput_items and the input requirements. That said, by deriving your classes from gr_sync_block, gr_sync_interpolator or gr_sync_decimator instead of gr_block, you can often avoid implementing forecast. set_output_multiple When implementing your general_work routine, it's occasionally convenient to have the run time system ensure that you are only asked to produce a number of output items that is a multiple of some particular value. This might occur if your algorithm naturally applies to a fixed sized block of data. Call set_output_multiple in your constructor to specify this requirement. The default output multiple is 1. Subclasses for common patterns gr_block allows tremendous flexibility with regard to the consumption of input streams and the production of output streams. Adroit use of forecast and consume allows variable rate blocks to be built. It is possible to construct blocks that consume data at different rates on each input, and produce output at a rate that is a function of the contents of the input data. On the other hand, it is very common for signal processing blocks to have a fixed relationship between the input rate and the output rate. Many are 1:1, while others have 1:N or N:1 relationships. Another common requirement is the need to examine more than one input sample to produce a single output sample. This is orthogonal to the relationship between input and output rate. For example, a non-decimating, non-interpolating FIR filter needs to examine N input samples for each output sample it produces, where N is the number of taps in the filter. However, it only consumes a single input sample to produce a single output. We call this concept "history", but you could also think of it as "look-ahead". gr_sync_block

gr_sync_block is derived from gr_block and implements a 1:1 block with optional history. Given that we know the input to output rate, certain simplifications are possible. http://www.gnu.org/software/gnuradio/doc/classgr__sync__block.html http://www.gnu.org/software/gnuradio/doc/classgr__block.html From the implementor's point-of-view, the primary change is that we define a work method instead of general_work. work has a slightly different calling sequence; It omits the unnecessary ninput_items parameter, and arranges for consume_each to be called on our behalf. /*! * \brief Just like gr_block::general_work, only this arranges to * call consume_each for you. * * The user must override work to define the signal processing code */ virtual int work (int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) = 0; This gives us fewer things to worry about, and less code to write. If the block requires history greater than 1, call set_history in the constructor, or any time the requirement changes. gr_sync_block provides a version of forecast that handles the history requirement. gr_sync_decimator gr_sync_decimator is derived from gr_sync_block and implements a N:1 block with optional history. http://www.gnu.org/software/gnuradio/doc/classgr__sync__decimator.html http://www.gnu.org/software/gnuradio/doc/classgr__sync__block.html gr_sync_interpolator gr_sync_interpolator is derived from gr_sync_block and implements a 1:N block with optional history. http://www.gnu.org/software/gnuradio/doc/classgr__sync__interpolator.html

Second Block: howto_square2_ff Given that we now know about gr_sync_block, the way howto_square_ff should really be implemented is by subclassing gr_sync_block. Here are the revised sources: Example 7, howto_square2_ff.h, Example 8, howto_square2_ff.cc. The accompanying files contain the additional test code. Example 7. howto_square2_ff.h 1 /* -*- c++ -*- */ 2 /* 3 * Copyright 2004 Free Software Foundation, Inc. 4 * 5 * This file is part of GNU Radio 6 * 7 * GNU Radio is free software; you can redistribute it and/or modify 8 * it under the terms of the GNU General Public License as published by 9 * the Free Software Foundation; either version 2, or (at your option) 10 * any later version. 11 * 12 * GNU Radio is distributed in the hope that it will be useful, 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 * GNU General Public License for more details. 16 * 17 * You should have received a copy of the GNU General Public License 18 * along with GNU Radio; see the file COPYING. If not, write to 19 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, 20 * Boston, MA 02111-1307, USA. 21 */ 22 #ifndef INCLUDED_HOWTO_SQUARE2_FF_H 23 #define INCLUDED_HOWTO_SQUARE2_FF_H 24 25 #include <gr_sync_block.h> 26 27 class howto_square2_ff; 28 29 /* 30 * We use boost::shared_ptr's instead of raw pointers for all access 31 * to gr_blocks (and many other data structures). The shared_ptr gets 32 * us transparent reference counting, which greatly simplifies storage 33 * management issues. This is especially helpful in our hybrid 34 * C++ / Python system. 35 * 36 * See http://www.boost.org/libs/smart_ptr/smart_ptr.htm

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77

* * As a convention, the _sptr suffix indicates a boost::shared_ptr */ typedef boost::shared_ptr<howto_square2_ff> howto_square2_ff_sptr; /*! * \brief Return a shared_ptr to a new instance of howto_square2_ff. * * To avoid accidental use of raw pointers, howto_square2_ff's * constructor is private. howto_make_square2_ff is the public * interface for creating new instances. */ howto_square2_ff_sptr howto_make_square2_ff (); /*! * \brief square2 a stream of floats. * \ingroup block * * This uses the preferred technique: subclassing gr_sync_block. */ class howto_square2_ff : public gr_sync_block { private: // The friend declaration allows howto_make_square2_ff to // access the private constructor. friend howto_square2_ff_sptr howto_make_square2_ff (); howto_square2_ff (); // private constructor

public: ~howto_square2_ff (); // public destructor // Where all the action really happens int work (int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; #endif /* INCLUDED_HOWTO_SQUARE2_FF_H */

Example 8. howto_square2_ff.cc 1 /* -*- c++ -*- */ 2 /* 3 * Copyright 2004 Free Software Foundation, Inc. 4 * 5 * This file is part of GNU Radio 6 * 7 * GNU Radio is free software; you can redistribute it and/or modify 8 * it under the terms of the GNU General Public License as published by 9 * the Free Software Foundation; either version 2, or (at your option) 10 * any later version. 11 * 12 * GNU Radio is distributed in the hope that it will be useful, 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 * GNU General Public License for more details. 16 * 17 * You should have received a copy of the GNU General Public License 18 * along with GNU Radio; see the file COPYING. If not, write to 19 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, 20 * Boston, MA 02111-1307, USA. 21 */ 22 23 /* 24 * config.h is generated by configure. It contains the results 25 * of probing for features, options etc. It should be the first 26 * file included in your .cc file. 27 */ 28 #ifdef HAVE_CONFIG_H 29 #include "config.h" 30 #endif 31 32 #include <howto_square2_ff.h> 33 #include <gr_io_signature.h> 34 35 /* 36 * Create a new instance of howto_square2_ff and return 37 * a boost shared_ptr. This is effectively the public constructor. 38 */ 39 howto_square2_ff_sptr 40 howto_make_square2_ff () 41 { 42 return howto_square2_ff_sptr (new howto_square2_ff ()); 43 } 44

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

/* * Specify constraints on number of input and output streams. * This info is used to construct the input and output signatures * (2nd & 3rd args to gr_block's constructor). The input and * output signatures are used by the runtime system to * check that a valid number and type of inputs and outputs * are connected to this block. In this case, we accept * only 1 input and 1 output. */ static const int MIN_IN = 1; // mininum number of input streams static const int MAX_IN = 1; // maximum number of input streams static const int MIN_OUT = 1; // minimum number of output streams static const int MAX_OUT = 1; // maximum number of output streams /* * The private constructor */ howto_square2_ff::howto_square2_ff () : gr_sync_block ("square2_ff", gr_make_io_signature (MIN_IN, MAX_IN, sizeof (float)), gr_make_io_signature (MIN_OUT, MAX_OUT, sizeof (float))) { // nothing else required in this example } /* * Our virtual destructor. */ howto_square2_ff::~howto_square2_ff () { // nothing else required in this example } int howto_square2_ff::work (int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float *) input_items[0]; float *out = (float *) output_items[0]; for (int i = 0; i < noutput_items; i++){ out[i] = in[i] * in[i]; } // Tell runtime system how many output items we produced.

91 return noutput_items; 92 }

Where to from Here? At this point, we've got a basic overview of how the system goes together. For more insight, I suggest that you look at the code of the system. The doxygen generated class hierarchy is a useful way to find things that might interest you. http://www.gnu.org/software/gnuradio/doc/hierarchy.html

Miscellaneous Tips Sources and Sinks Sources and sinks are derived from gr_sync_block. The only thing different about them is that sources have no inputs and sinks have no outputs. This is reflected in the gr_io_signatures that are passed to the gr_sync_block constructor. Take a look at gr_file_source.{h,cc} and gr_file_sink.{h,cc} for some very straight-forward examples. Debugging with gdb If your block isn't working, and you can't sort it out through python test cases or a few printfs in the code, you may want to use gdb to debug it. The trick of course is that all of GNU Radio, including your new block, is dynamically loaded into python for execution. Try this: In your python test code, after the relevant imports, print out the process id and wait for a keystroke. In another window run gdb and tell it to attach to the python process with the given process id. At this point you can set breakpoints or whatever in your code. Go back to the python window and hit Enter so it'll continue. #!/usr/bin/env python from gnuradio import gr from gnuradio import my_buggy_module # insert this in your test code... import os print 'Blocked waiting for GDB attach (pid = %d)' % (os.getpid(),) raw_input ('Press Enter to continue: ') # remainder of your test code follows...

Another SNAFU you might run into is that gdb 6.2 isn't able to set breakpoints in the constructors or destructors generated by g++ 3.4. In this case, insert a call to the nop function gri_debugger_hook in the constructor and recompile. Load the code as before and set a break point on gri_debugger_hook.

Performance Measurement with oprofile Oprofile is your friend. See http://oprofile.sourceforge.net.

UHD Start
The UHD is the "Universal Software Radio Peripheral" hardware driver. It works on all major platforms (Linux, Windows, and Mac); and can be built with GCC, Clang, and MSVC compilers. The goal of the UHD is to provide a host driver and API for current and future Ettus Research products. Users will be able to use the UHD driver standalone or with 3rd party applications such as Gnuradio, Labview, or Simulink. See below for the Gnuradio instructions

Help and Support

Discussions about UHD, USRP hardware, and 3rd party software should go to:

usrp-users@lists.ettus.com

Discussions involving Gnuradio and UHD/USRP hardware should go to:

discuss-gnuradio@gnu.org

If you plan on trolling the list, please send troll-mail to:

donotreply@ettus.com

Help us help you by providing essential details:


What hardware are you using? (daughterboards, motherboards, version numbers, etc...) What software are you using? (gnuradio, simulink, labview, c++ application, etc...) Can you attach a minimal example that demonstrates the problem? Screenshots, time domain and frequency plots can also be helpful.

Source code Note: Users building from source should use the images for the master branch (see binary downloads).

Option 1: Clone the repository: git clone git://code.ettus.com/ettus/uhd.git -- Is your corporate or university firewall blocking the git protocol? -- Try this http mirror instead. The mirror is updated daily. git clone http://github.com/EttusResearch/UHD-Mirror.git Option 2: Download an archive here: https://github.com/EttusResearch/UHDMirror/archives/master

Building Images Pre-built FPGA and firmware images are available in the binary downloads section. To build the images yourself, the relevant commands can be found in the images Makefile: http://code.ettus.com/redmine/ettus/projects/uhd/repository/revisions/master/entry/images/Makef ile

Binary downloads The following link contain binary builds of each release, along with FPGA, firmware, and kernel images:

Each release is associated with a set of FPGA, firmware, and kernel images. The code for each release has a corresponding tag in the git repository. Images for the master branch change periodically to track the code development.

Master images: Download images for master branch :(most-recent): http://files.ettus.com/uhd_releases/master_images

UHD - Build Guide


Table of Contents

Build Dependencies o Git o C++ compiler o CMake o Boost o LibUSB o Python o Cheetah o Doxygen o Docutils Build Instructions (Unix) o Generate Makefiles with cmake o Build and install o Setup the library path (Linux) o Setup the library path (Mac OS X) Build Instructions (Windows) o Generate the project with cmake o LibUSB cmake notes o Build the project in MSVC o Build the project in MSVC (command line) o Setup the PATH environment variable Post-Install Tasks

Build Dependencies Linux Notes: This is dependent on the distribution you are using, but most, if not all, of the dependencies should be available in the package repositories for your package manager. Mac OS X Notes: Install the "Xcode Developer Tools" to get the build tools (gcc and make). Use MacPorts to get the Boost and Cheetah dependencies. Other dependencies can be downloaded as dmg installers from the web. Windows Notes: The dependencies can be acquired through installable exe files. Usually, the windows installer can be found on the project's website. Some projects do not host windows installers, and if this is the case, follow the auxiliary download url for the windows installer (below).

Git Required to check out the repository. On windows, install cygwin with git support to checkout the repository, or install msysgit from http://code.google.com/p/msysgit/downloads/list C++ compiler The following compilers are known to work:

GCC Clang MSVC

CMake

Purpose: generates project build files Version: at least 2.6 Usage: build time (required) Download URL: http://www.cmake.org/cmake/resources/software.html

Boost

Purpose: C++ library Version: at least 1.36 unix, at least 1.40 windows Usage: build time + run time (required) Download URL: http://www.boost.org/users/download/ Download URL (windows installer): http://www.boostpro.com/download

LibUSB

Purpose: USB-based hardware support Version: at least 1.0 Usage: build time + run time (optional) Download URL: http://sourceforge.net/projects/libusb/files/libusb-1.0/ Download URL (windows binaries): http://www.libusb.org/wiki/windows_backend#LatestBinarySnapshots

Python

Purpose: used by Cheetah and utility scripts Version: at least 2.6 Usage: build time + run time utility scripts (required) Download URL: http://www.python.org/download/

Cheetah

Purpose: source code generation Version: at least 2.0 Usage: build time (required) Download URL: http://www.cheetahtemplate.org/download.html Download URL (windows installer): http://feisley.com/python/cheetah/

Alternative method: Install setuptools, and use the easy_install command to install Cheetah. http://pypi.python.org/pypi/setuptools Doxygen

Purpose: generates html api documentation Usage: build time (optional) Download URL: http://www.stack.nl/~dimitri/doxygen/download.html#latestsrc

Docutils

Purpose: generates html user manual Usage: build time (optional) Download URL: http://docutils.sourceforge.net/

Build Instructions (Unix) Generate Makefiles with cmake cd <uhd-repo-path>/host mkdir build cd build cmake ../ Additionally, configuration variables can be passed into cmake via the command line. The following common-use configuration variables are listed below:

For a custom install prefix: -DCMAKE_INSTALL_PREFIX=<install-path> To install libs into lib64: cmake -DLIB_SUFFIX=64

Example usage: cmake -DCMAKE_INSTALL_PREFIX=/opt/uhd ../

Build and install make make test sudo make install

Setup the library path (Linux) Make sure that libuhd.so is in your LD_LIBRARY_PATH or add it to /etc/ld.so.conf and make sure to run: sudo ldconfig

Setup the library path (Mac OS X) Make sure that libuhd.dylib is in your DYLD_LIBRARY_PATH

Build Instructions (Windows) Generate the project with cmake


Open the cmake gui program. Set the path to the source code: <uhd-repo-path>/host Set the path to the build directory: <uhd-repo-path>/host/build Make sure that the paths do not contain spaces. Click configure and select the MSVC compiler. Set the build variables and click configure again. Click generate and a project file will be created in the build directory.

LibUSB cmake notes On Windows, cmake does not have the advantage of pkg-config, so we must manually tell cmake how to locate the LibUSB header and lib.

From the cmake gui, select "Advanded View" Set LIBUSB_INCLUDE_DIR to the directory with "libusb.h". Set LIBUSB_LIBRARIES to the full path for "libusb-1.0.lib". o Recommend the static libusb-1.0.lib to simplify runtime dependencies. Check the box to enable USB support, click configure and generate.

Build the project in MSVC


Open the generated project file in MSVC. Change the build type from "Debug" to "Release". Select the build all target, right click, and choose build. Select the install target, right click, and choose build.

Note: you may not have permission to build the install target. You need to be an administrator or to run MSVC as administrator. Build the project in MSVC (command line) Open the Visual Studio Command Prompt Shorcut: cd <uhd-repo-path>\host\build DevEnv uhd.sln /build Release /project ALL_BUILD DevEnv uhd.sln /build Release /project INSTALL

Setup the PATH environment variable

Add the uhd bin path to %PATH% (usually c:\program files\uhd\bin)

Note: The interface for editing environment variable paths in Windows is very poor. I recommend using "Rapid Environment Editor" (http://www.rapidee.com) over the default editor.

USB-based devices UHD - Transport Application Notes


Introduction A transport is the layer between the packet interface and a device IO interface. The advanced user can pass optional parameters into the underlying transport layer through the device address. These optional parameters control how the transport object allocates memory, resizes kernel buffers, spawns threads, etc. When not spcified, the transport layer will use values for these parameters that are known to perform well on a variety of systems. The transport parameters are defined below for the various transports in the UHD: UDP transport (sockets) The UDP transport is implemented with user-space sockets. This means standard Berkeley sockets API using send()/recv(). Transport parameters The following parameters can be used to alter the transport's default behavior:

recv_frame_size: The size of a single receive buffer in bytes num_recv_frames: The number of receive buffers to allocate send_frame_size: The size of a single send buffer in bytes num_send_frames: The number of send buffers to allocate

Note1: num_recv_frames does not affect performance. Note2: num_send_frames does not affect performance. Note3: recv_frame_size and send_frame_size can be used to increase or decrease the maximum number of samples per packet. The frame sizes default to an MTU of 1472 bytes per IP/UDP packet, and may be increased if permitted by your network hardware. Flow control parameters The host-based flow control expects periodic update packets from the device. These update packets inform the host of the last packet consumed by the device, which allows the host to determine throttling conditions for the transmission of packets. The following mechanisms affect the transmission of periodic update packets:

ups_per_fifo: The number of update packets for each FIFO's worth of bytes sent into the device ups_per_sec: The number of update packets per second (defaults to 20 updates per second)

Resize socket buffers It may be useful increase the size of the socket buffers to move the burden of buffering samples into the kernel, or to buffer incoming samples faster than they can be processed. However, if your application cannot process samples fast enough, no amount of buffering can save you. The following parameters can be used to alter socket's buffer sizes:

recv_buff_size: The desired size of the receive buffer in bytes send_buff_size: The desired size of the send buffer in bytes

Note: Large send buffers tend to decrease transmit performance. Latency Optimization Latency is a measurement of the time it takes a sample to travel between the host and device. Most computer hardware and software is bandwidth optimized which may negatively affect latency. If your application has strict latency requirements, please consider the following notes: Note1: The time taken by the device to populate a packet is proportional to the sample rate. Therefore, to improve receive latency, configure the transport for a smaller frame size. Note2: For overall latency improvements, look for "Interrupt Coalescing" settings for your OS and ethernet chipset. It seems the Intel ethernet chipsets offer fine-grained control in Linux. Also, consult:

http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.prftu ngd/doc/prftungd/interrupt_coal.htm

Linux specific notes On linux, the maximum buffer sizes are capped by the sysctl values net.core.rmem_max and net.core.wmem_max. To change the maximum values, run the following commands: sudo sysctl -w net.core.rmem_max=<new value> sudo sysctl -w net.core.wmem_max=<new value> Set the values permanently by editing /etc/sysctl.conf

Windows specific notes On Windows, it is important to change the default UDP behavior such that 1500 byte packets still travel through the fast path of the sockets stack. FastSendDatagramThreshold registry key to change documented here:

http://www.microsoft.com/windows/windowsmedia/howto/articles/optimize_web.aspx#a ppendix_e

USB transport (libusb) The USB transport is implemented with libusb. Libusb provides an asynchronous API for USB bulk transfers. Transport parameters The following parameters can be used to alter the transport's default behavior:

recv_frame_size: The size of a single receive transfers in bytes num_recv_frames: The number of simultaneous receive transfers send_frame_size: The size of a single send transfers in bytes num_send_frames: The number of simultaneous send transfers

Setup Udev for USB (Linux) On Linux, Udev handles USB plug and unplug events. The following commands install a Udev rule so that non-root users may access the device: cd <install-path>/share/uhd/utils sudo cp uhd-usrp.rules /etc/udev/rules.d/ sudo udevadm control --reload-rules Install USB driver (Windows) A driver package must be installed to use a USB-based product with UHD:

Download the driver from the UHD wiki page. Unzip the file into a known location. We will refer to this as the <directory>. Open the device manager and plug-in the USRP. You will see an unrecognized USB device in the device manager.

Right click on the unrecognized USB device and select update/install driver software (may vary for your OS). In the driver installation wizard, select "browse for driver", browse to the <directory>, and select the .inf file. Continue through the installation wizard until the driver is installed.

Using UHD Windows installer? Install MSVC redistributable package http://www.microsoft.com/downloads/en/details.aspx?FamilyID=a7b7a05e-6de6-4d3a-a42337bf0912db84 Installed UHD from source? Download the images package: http://code.ettus.com/redmine/ettus/projects/uhd/wiki#Binarydownloads

Images installation instructions: UHD - Firmware and FPGA Image Application Notes: Images Overview Every USRP device must be loaded with special firmware and FPGA images. The methods of loading images into the device varies among devices:

USRP1: The host code will automatically load the firmware and FPGA at runtime. USRP2: The user must manually write the images onto the USRP2 SD card. USRP-N Series: The user must manually transfer the images over ethernet. USRP-E Series: The host code will automatically load the FPGA at runtime. USRP-B Series: The host code will automatically load the FPGA at runtime.

Pre-built images Pre-built images are available for download. See the UHD wiki for the download link. The pre-built images come in two forms:

bundled with UHD in a platform-specific installer stand-alone platform-independent archive files

Platform installers The UNIX-based installers will install the images into /usr/share/uhd/images. On windows, the images will be installed to <install-path>/share/uhd/images. Archive install When installing images from an archive, there are two options:

Option 1: Unpack the archive into the UHD installation prefix. The UHD will always search <installpath>/share/uhd/images for image files. Where <install-path> was set by the CMAKE_INSTALL_PREFIX at configure-time. Option 2: Unpack the archive anywhere and set the UHD_IMAGE_PATH environment variable. The UHD_IMAGE_PATH may contain a list of directories to search for image files.

Building images The UHD source repository comes with the source code necessary to build both firmware and FPGA images for all supported devices. The build commands for a particular image can be found in <uhd-repo-path>/images/Makefile. Xilinx FPGA builds Xilinx ISE 12.x and up is required to build the Xilinx FPGA images. The build requires that you have a unix-like environment with make. Make sure that xtclsh from the Xilinx ISE bin directory is in your $PATH. See <uhd-repo-path>/fpga/usrp2/top/* Microblaze firmware builds The Microblaze GCC compiler from the Xilinx EDK is required to build the Microblaze firmware images. The build requires that you have a unix-like environment with autotools and make. Make sure that mb-gcc from the Xilinx EDK/microblaze directory is in your $PATH. See <uhd-repo-path>/firmware/microblaze Altera FPGA builds Quartus is required to build the Altera FPGA images. Pre-built images can also be found in <uhd-repo-path>/fpga/usrp1/rbf See <uhd-repo-path>/fpga/usrp1/toplevel/* FX2 firmware builds The sdcc compiler is required to build the FX2 firmware images. The build requires that you have a unix-like environment with autotools and make. See <uhd-repo-path>/firmware/fx2

******************************************

Application Notes
UHD - General Application Notes Tuning notes Two-stage tuning process A USRP device has two stages of tuning:

RF front-end: translates bewteen RF and IF DSP: translates between IF and baseband

In a typical use-case, the user specifies an overall center frequency for the signal chain. The RF front-end will be tuned as close as possible to the center frequency, and the DSP will account for the error in tuning between target frequency and actual frequency. The user may also explicitly control both stages of tuning through through the tune_request_t object, which allows for more advanced tuning. In general, Using UHD's advanced tuning is highly recommended as it makes it easy to move the DC component out of your band-of-interest. This can be done by passing your desired LO offset to the tune_request_t object, and letting UHD handle the rest. Tuning the receive chain: //tuning to a desired center frequency usrp->set_rx_freq(target_frequency_in_hz); --OR-//advanced tuning with tune_request_t uhd::tune_request_t tune_req(target_frequency_in_hz, desired_lo_offset); //fill in any additional/optional tune request fields... usrp->set_rx_freq(tune_req); More information can be fonud in tune_request.hpp. RF front-end settling time After tuning, the RF front-end will need time to settle into a usable state. Typically, this means that the local oscillators must be given time to lock before streaming begins. Lock time is not consistent; it varies depending upon the device and requested settings. After tuning and before

streaming, the user should wait for the "lo_locked" sensor to become true, or sleep for a conservative amount of time (perhaps a second). Pseudo-code for dealing with settling time after tuning on receive: usrp->set_rx_freq(...); sleep(1); usrp->issue_stream_command(...); --OR-usrp->set_rx_freq(...); while (not usrp->get_rx_sensor("lo_locked").to_bool()){ //sleep for a short time in milliseconds } usrp->issue_stream_command(...); Specifying the subdevice to use A subdevice specification string for USRP family devices is composed of: <motherboard slot name>:<daughterboard frontend name> Ex: The subdev spec markup string to select a WBX on slot B. B:0 Ex: The subdev spec markup string to select a BasicRX on slot B. B:AB -- OR -B:A -- OR -B:B USRP Family Motherboard Slot Names All USRP family motherboards have a first slot named A:. The USRP1 has two daughterboard subdevice slots, known as A: and B:.

Daughterboard Frontend Names Daughterboard frontend names can be used to specify which signal path is used from a daughterboard. Most daughterboards have only one frontend :0. A few daughterboards (Basic, LF and TVRX2) have multiple frontend names available. The frontend names are documented in the Daughterboard Application Notes: http://files.ettus.com/uhd_docs/manual/html/dboards.html

Overflow/Underflow notes Note: The following overflow/underflow notes do not apply to USRP1, which does not support the advanced features available in newer products. Overflow notes When receiving, the device produces samples at a constant rate. Overflows occurs when the host does not consume data fast enough. When UHD detects the overflow, it prints an "O" to stdout, and pushes an inline message packet into the receive stream. Network-based devices: The host does not back-pressure the receive stream. When the kernel's socket buffer becomes full, it will drop subsequent packets. UHD detects the overflow as a discontinuity in the packet's sequence numbers, and muxes an inline message packet into the receive stream. Other devices: The host back-pressures the receive stream. Therefore, overflows always occur in the device itself. When the device's internal buffers become full, streaming is shutoff, and an inline message packet is sent to the host. If the device was in continuous streaming mode, the UHD will automatically restart streaming. Underflow notes When transmitting, the device consumes samples at a constant rate. Underflow occurs when the host does not produce data fast enough. When the UHD detects underflow, it prints an "U" to stdout, and pushes a message packet into the async message stream.

Threading notes Thread safety notes For the most part, UHD is thread-safe. Please observe the following limitations: Fast-path thread requirements: There are three fast-path methods for a device: send(), recv(), and recv_async_msg(). All three methods are thread-safe and can be called from different thread contexts. For performance, the user should call each method from a separate thread context. These methods can also be used in a non-blocking fashion by using a timeout of zero. Slow-path thread requirements: It is safe to change multiple settings simultaneously. However, this could leave the settings for a device in an uncertain state. The is because changing one setting could have an impact on how a call affects other settings. Example: setting the channel mapping affects how the antennas are set. It is recommended to use at most one thread context for manipulating device settings. Thread priority scheduling When the UHD spawns a new thread it may try to boost the thread's scheduling priority. When setting the priority fails, the UHD prints out an error. This error is harmless, it simply means that the thread will have a normal scheduling priority. Linux Notes: Non-privileged users need special permission to change the scheduling priority. Add the following line to /etc/security/limits.conf: @<my_group> - rtprio 99

Replace <my_group> with a group to which your user belongs. Settings will not take effect until the user has logged in and out. Misc notes Support for dynamically loadable modules For a module to be loaded at runtime, it must be:

found in the UHD_MODULE_PATH environment variable, installed into the <install-path>/share/uhd/modules directory, or installed into /usr/share/uhd/modules directory (unix only).

Disabling or redirecting prints to stdout The user can disable the UHD library from printing directly to stdout by registering a custom message handler. The handler will intercept all messages, which can be dropped or redirected. Only one handler can be registered at a time. Make "register_handler" your first call into UHD: #include <uhd/utils/msg.hpp> void my_handler(uhd::msg::type_t type, const std::string &msg){ //handle the message... } uhd::msg::register_handler(&my_handler); ********************************* UHD - Device Identification Notes Identifying USRPs Devices are addressed through key/value string pairs. These string pairs can be used to narrow down the search for a specific device or group of devices. Most UHD utility applications and examples have a --args parameter that takes a device address; where the device address is expressed as a delimited string. See the documentation in types/device_addr.hpp for reference. Common device identifiers Every device has several ways of identifying it on the host system: Identifier Key Serial Address Name Type Notes

serial globally unique identifier addr unique identifier on a network name optional user-set identifier type hardware series identifier

Device discovery via command line Devices attached to your system can be discovered using the "uhd_find_devices" program. The find devices program scans your system for supported devices and prints out an enumerated list

of discovered devices and their addresses. The list of discovered devices can be narrowed down by specifying device address args. uhd_find_devices Device address arguments can be supplied to narrow the scope of the search. uhd_find_devices --args="type=usrp1" -- OR -uhd_find_devices --args="serial=12345678" Device discovery through the API The device::find() API call searches for devices and returns a list of discovered devices. uhd::device_addr_t hint; //an empty hint discovers all devices uhd::device_addrs_t dev_addrs = uhd::device::find(hint); The hint argument can be populated to narrow the scope of the search. uhd::device_addr_t hint; hint["type"] = "usrp1"; uhd::device_addrs_t dev_addrs = uhd::device::find(hint); -- OR -uhd::device_addr_t hint; hint["serial"] = "12345678"; uhd::device_addrs_t dev_addrs = uhd::device::find(hint); Device properties Properties of devices attached to your system can be probed with the "uhd_usrp_probe" program. The usrp probe program constructs an instance of the device and prints out its properties; properties such as detected daughter-boards, frequency range, gain ranges, etc... Usage: uhd_usrp_probe --args <device-specific-address-args>

Naming a USRP For convenience purposes, users may assign a custom name to their USRPs. The USRP can then be identified via name, rather than a difficult to remember serial or address. A name has the following properties:

is composed of ASCII characters is between 0 and 20 characters is not required to be unique

Set a custom name Run the following commands: cd <install-path>/share/uhd/utils ./usrp_burn_mb_eeprom --args=<optional device args> --key=name --val=lab1_xcvr Discovery via name The keyword "name" can be used to narrow the scope of the search. Example with the find devices utility: uhd_find_devices --args="name=lab1_xcvr" -- OR -uhd_find_devices --args="type=usrp1, name=lab1_xcvr"

************************************

UHD - USRP1 Application Notes Specify a non-standard image The standard USRP1 images installer comes with two FPGA images:

usrp1_fpga.rbf: 2 DDCs + 2 DUCs usrp1_fpga_4rx.rbf: 4 DDCs + 0 DUCs

By default, the USRP1 uses the FPGA image with 2 DDCs and 2 DUCs. However, a device address parameter can be used to override the FPGA image selection to use an alternate or a custom FPGA image. See the images application notes for installing custom images. Example device address string representations to specify non-standard firmware and/or FPGA images: fpga=usrp1_fpga_4rx.rbf -- OR -fw=usrp1_fw_custom.ihx -- OR -fpga=usrp1_fpga_4rx.rbf, fw=usrp1_fw_custom.ihx Missing and emulated features The USRP1 FPGA does not have the necessary space to support the advanced streaming capabilities that are possible with the newer USRP devices. Some of these features are emulated in software to support the API. List of emulated features

Setting the current device time Getting the current device time Transmitting at a specific time Transmitting a specific number of samples Receiving at a specific time Receiving a specific number of samples End of burst flags for transmit/receive Notification on late stream command Notification on late transmit packet Notification on underflow or overflow Notification on broken chain error

Note: These emulated features rely on the host system's clock for timed operations, and therefore may not have sufficient precision for the application. List of missing features

Start of burst flags for transmit/receive

Hardware setup notes External clock modification The USRP can be modified to accept an external clock reference instead of the 64MHz onboard reference.

Solder SMA (LTI-SASF54GT) connector to J2001 Move 0 ohm 0603 resistor R2029 to R2030 Move 0.01uF 0603 capacitor C925 to C926 Remove 0.01uF 0603 capacitor C924

The new external clock needs to be a square wave between +7dBm and +15dBm After the hardware modification, the user should burn the setting into the EEPROM, so UHD can initialize with the correct clock rate. Run the following commands to record the setting into the EEPROM: cd <install-path>/share/uhd/utils ./usrp_burn_mb_eeprom --args=<optional device args> --key=mcr --val=<rate> The user may override the clock rate specified in the EEPROM by using a device address: Example: uhd_usrp_probe --args="mcr=52e6" *****************************************

UHD - USRP2 and N Series Application Notes Load the images onto the SD card (USRP2 only) Warning! Use the usrp2_card_burner.py with caution. If you specify the wrong device node, you could overwrite your hard drive. Make sure that --dev= specifies the SD card. Warning! It is possible to use 3rd party SD cards with the USRP2. However, certain types of SD cards will not interface with the CPLD:

Cards can be SDHC, which is not a supported interface. Cards can have unexpected timing characteristics.

For these reasons, we recommend that you use the SD card that was supplied with the USRP2. Use the card burner tool (unix) sudo <install-path>/share/uhd/utils/usrp2_card_burner_gui.py -- OR -cd <install-path>/share/uhd/utils sudo ./usrp2_card_burner.py --dev=/dev/sd<XXX> --fpga=<path_to_fpga_image> sudo ./usrp2_card_burner.py --dev=/dev/sd<XXX> --fw=<path_to_firmware_image> Use the --list option to get a list of possible raw devices. The list result will filter out disk partitions and devices too large to be the sd card. The list option has been implemented on Linux, Mac OS X, and Windows. Use the card burner tool (windows) <path_to_python.exe> <install-path>/share/uhd/utils/usrp2_card_burner_gui.py Load the images onto the on-board flash (USRP-N Series only) The USRP-N Series can be reprogrammed over the network to update or change the firmware and FPGA images. When updating images, always burn both the FPGA and firmware images before power cycling. This ensures that when the device reboots, it has a compatible set of images to boot into. Note: Different hardware revisions require different FPGA images. Determine the revision number from the sticker on the rear of the chassis. Use this number to select the correct FPGA image for your device.

Use the net burner tool (unix) <install-path>/share/uhd/utils/usrp_n2xx_net_burner_gui.py -- OR -cd <install-path>/share/uhd/utils ./usrp_n2xx_net_burner.py --addr=<ip address> --fw=<path for firmware image> ./usrp_n2xx_net_burner.py --addr=<ip address> --fpga=<path to FPGA image> Use the net burner tool (Windows) <path_to_python.exe> <install-path>/share/uhd/utils/usrp_n2xx_net_burner_gui.py Device recovery and bricking Its possible to put the device into an unusable state by loading bad images. Fortunately, the USRP-N Series can be booted into a safe (read-only) image. Once booted into the safe image, the user can once again load images onto the device. The safe-mode button is a pushbutton switch (S2) located inside the enclosure. To boot into the safe image, hold-down the safe-mode button while power-cycling the device. Continue to holddown the button until the front-panel LEDs blink and remain solid. When in safe-mode, the USRP-N device will always have the IP address 192.168.10.2

Setup networking The USRP2 only supports gigabit ethernet, and will not work with a 10/100 Mbps interface. However, a 10/100 Mbps interface can be connected indirectly to a USRP2 through a gigabit ethernet switch. Setup the host interface The USRP2 communicates at the IP/UDP layer over the gigabit ethernet. The default IP address of the USRP2 is 192.168.10.2 You will need to configure the host's ethernet interface with a static IP address to enable communication. An address of 192.168.10.1 and a subnet mask of 255.255.255.0 is recommended. Note: When using the UHD, if an IP address for the USRP2 is not specified, the software will use UDP broadcast packets to locate the USRP2. On some systems, the firewall will block UDP broadcast packets. It is recommended that you change or disable your firewall settings.

Multiple devices per host


For maximum throughput, one ethernet interface per USRP2 is recommended, although multiple devices may be connected via a gigabit ethernet switch. In any case, each ethernet interface should have its own subnet, and the corresponding USRP2 device should be assigned an address in that subnet. Example: Configuration for USRP2 device 0:

Ethernet interface IPv4 address: 192.168.10.1 Ethernet interface subnet mask: 255.255.255.0 USRP2 device IPv4 address: 192.168.10.2

Configuration for USRP2 device 1:


Ethernet interface IPv4 address: 192.168.20.1 Ethernet interface subnet mask: 255.255.255.0 USRP2 device IPv4 address: 192.168.20.2

Change the USRP2's IP address


You may need to change the USRP2's IP address for several reasons:

to satisfy your particular network configuration to use multiple USRP2s on the same host computer to set a known IP address into USRP2 (in case you forgot)

Method 1: To change the USRP2's IP address you must know the current address of the USRP2, and the network must be setup properly as described above. Run the following commands: cd <install-path>/share/uhd/utils ./usrp_burn_mb_eeprom --args=<optional device args> --key=ip-addr --val=192.168.10.3 Method 2 (Linux Only): This method assumes that you do not know the IP address of your USRP2. It uses raw ethernet packets to bypass the IP/UDP layer to communicate with the USRP2. Run the following commands: cd <install-path>/share/uhd/utils sudo ./usrp2_recovery.py --ifc=eth0 --new-ip=192.168.10.3 Communication problems When setting up a development machine for the first time, you may have various difficulties communicating with the USRP device. The following tips are designed to help narrow-down and diagnose the problem.

Firewall issues When the IP address is not specified, the device discovery sends broadcast UDP packets from each ethernet interface. Many firewalls will block the replies to these broadcast packets. If disabling your system's firewall, or specifying the IP address yeilds a discovered device, then your firewall may be blocking replies to UDP broadcast packets. If this is the case, we recommend that you disable the firewall, or create a rule to allow all incoming packets with UDP source port 49152. Ping the device The USRP will reply to icmp echo requests. A successful ping response means that the device has booted properly, and that it is using the expected IP address. ping 192.168.10.2 Monitor the serial output Read the serial port to get debug verbose from the embedded microcontroller. The microcontroller prints useful information about IP addresses, MAC addresses, control packets, fast-path settings, and bootloading. Use a standard USB to 3.3v-level serial converter at 230400 baud. Connect GND to the converter ground, and connect TXD to the converter receive. The RXD pin can be left unconnected as this is only a one-way communication.

USRP2: Serial port located on the rear edge N210: Serial port located on the left side

Monitor the host network traffic Use wireshark to monitor packets sent to and received from the device.

Addressing the device Single device configuration In a single-device configuration, the USRP device must have a unique IPv4 address on the host computer. The USRP can be identified through its IPv4 address, resolvable hostname, or by other means. See the application notes on device identification. Use this addressing scheme with the single_usrp interface. http://files.ettus.com/uhd_docs/manual/html/identification.html Example device address string representation for a USRP2 with IPv4 address 192.168.10.2 addr=192.168.10.2

Multiple device configuration In a multi-device configuration, each USRP device must have a unique IPv4 address on the host computer. The device address parameter keys must be suffixed with the device index. Each parameter key should be of the format <key><index>. Use this addressing scheme with the multi_usrp interface.

The order in which devices are indexed corresponds to the indexing of the transmit and receive channels. The key indexing provides the same granularity of device identification as in the single device case.

Example device address string representation for 2 USRP2s with IPv4 addresses 192.168.10.2 and 192.168.20.2 addr0=192.168.10.2, addr1=192.168.20.2

Using the MIMO Cable The MIMO cable allows two USRP devices to share reference clocks, time synchronization, and the ethernet interface. One of the devices will sink its clock and time references to the MIMO cable. This device will be referred to as the slave, and the other device, the master.

The slave device acquires the clock and time references from the master device. The master and slave may be used individually or in a multi-device configuration. External clocking is optional, and should only be supplied to the master device.

Shared ethernet mode In shared ethernet mode, only one device in the configuration can be attached to the ethernet.

Clock reference, time reference, and data are communicated over the MIMO cable. Both master and slave must have different IPv4 addresses in the same subnet.

Dual ethernet mode In dual ethernet mode, both devices in the configuration must be attached to the ethernet.

Only clock reference and time reference are communicated over the MIMO cable. Both master and slave must have different IPv4 addresses in different subnets.

Configuring the slave In order for the slave to synchronize to the master over MIMO cable, the following clock configuration must be set on the slave device: uhd::clock_config_t clock_config; clock_config.ref_source = uhd::clock_config_t::REF_MIMO; clock_config.pps_source = uhd::clock_config_t::PPS_MIMO; usrp->set_clock_config(clock_config, slave_index);

Hardware setup notes Front panel LEDs The LEDs on the front panel can be useful in debugging hardware and software issues. The LEDs reveal the following about the state of the device:

LED A: transmitting LED B: mimo cable link LED C: receiving LED D: firmware loaded LED E: reference lock LED F: CPLD loaded

Ref Clock - 10MHz Using an external 10MHz reference clock, square wave will offer the best phase noise performance, but sinusoid is acceptable. The reference clock requires the following power level:

USRP2 5 to 15dBm N2XX 0 to 15dBm

PPS - Pulse Per Second Using a PPS signal for timestamp synchronization requires a square wave signal with the following amplitude:

USRP2 5Vpp N2XX 3.3 to 5Vpp

Test the PPS input with the following app:

<args> are device address arguments (optional if only one USRP is on your machine)

cd <install-path>/share/uhd/examples ./test_pps_input --args=<args>

Internal GPSDO Please see the Internal GPSDO Application Notes for information on configuring and using the internal GPSDO. http://files.ettus.com/uhd_docs/manual/html/gpsdo.html

Miscellaneous Available Sensors The following sensors are available for the USRP2/N-Series motherboards; they can be queried through the API.

mimo_locked - clock reference locked over the MIMO cable ref_locked - clock reference locked (internal/external) other sensors are added when the GPSDO is enabled

Multiple RX channels There are two complete DDC chains in the FPGA. In the single channel case, only one chain is ever used. To receive from both channels, the user must set the RX subdevice specification. This hardware has only one daughterboard slot, which has been aptly named slot "A". In the following example, a TVRX2 is installed. Channel 0 is sourced from subdevice RX1, channel 1 is sourced from subdevice RX2: usrp->set_rx_subdev_spec("A:RX1 A:RX2");

**********************************

UHD - USRP-B1XX Series Application Notes

Specify a non-standard image The UHD will automatically select the USRP B-Series images from the installed images package. The image selection can be overridden with the "fpga" and "fw" device address parameters. Example device address string representations to specify non-standard images: fpga=usrp_b100_fpga_firmware.bin -- OR -fw=usrp_b100_fw_firmware.ihx

Changing the master clock rate The master clock rate of the USRP embedded feeds both the FPGA DSP and the codec chip. Hundreds of rates between 32MHz and 64MHz are available. A few notable rates are:

64MHz - maximum rate of the codec chip 61.44MHz - good for UMTS/WCDMA applications 52Mhz - good for GSM applications

Set 61.44MHz - uses external VCXO To use the 61.44MHz clock rate, the USRP embedded will require two jumpers to be moved.

J16 is a two pin header, remove the jumper (or leave it on pin1 only) J15 is a three pin header, move the jumper to (pin1, pin2)

Note: See instructions below to communicate the desired clock rate into the UHD.

Set other rates - uses internal VCO To use other clock rates, the jumpers will need to be in the default position.

J16 is a two pin header, move the jumper to (pin1, pin2) J15 is a three pin header, move the jumper to (pin2, pin3)

To communicate the desired clock rate into the UHD, specify the a special device address argument, where the key is "master_clock_rate" and the value is a rate in Hz. Example: uhd_usrp_probe --args="master_clock_rate=52e6"

Hardware setup notes Front panel LEDs The LEDs on the front panel can be useful in debugging hardware and software issues. The LEDs reveal the following about the state of the device:

LED A: transmitting LED B: fpga loaded LED C: receiving LED D: fpga loaded LED E: reference lock LED F: board power

Miscellaneous Available Sensors The following sensors are available; they can be queried through the API.

ref_locked - clock reference locked (internal/external) **********************************************

UHD - USRP-E1XX Series Application Notes Specify a non-standard image UHD will automatically select the USRP-Embedded FPGA image from the installed images package. The FPGA image selection can be overridden with the "fpga" device address parameter. Example device address string representations to specify non-standard FPGA image: fpga=usrp_e100_custom.bin

Changing the master clock rate The master clock rate of the USRP-Embedded feeds both the FPGA DSP and the codec chip. Hundreds of rates between 32MHz and 64MHz are available. A few notable rates are:

64MHz - maximum rate of the codec chip 61.44MHz - good for UMTS/WCDMA applications 52Mhz - good for GSM applications

Set 61.44MHz - uses external VCXO To use the 61.44MHz clock rate with the USRP-Embedded, two jumpers must be moved on the device.

J16 is a two pin header, remove the jumper (or leave it on pin1 only) J15 is a three pin header, move the jumper to (pin1, pin2)

Note: See instructions below to communicate the desired clock rate into the UHD. Set other rates - uses internal VCO To use other clock rates, the jumpers will need to be in the default position.

J16 is a two pin header, move the jumper to (pin1, pin2) J15 is a three pin header, move the jumper to (pin2, pin3)

To communicate the desired clock rate into the UHD, specify the a special device address argument, where the key is "master_clock_rate" and the value is a rate in Hz. Example: uhd_usrp_probe --args="master_clock_rate=52e6"

Clock Synchronization Ref Clock - 10MHz The E1xx has a 10MHz TCXO which can be used to discipline the flexible clocking by selecting REF_INT for the clock_config_t. Alternately, an external 10MHz reference clock can be supplied by soldering a connector.

Connector J10 (REF_IN) needs MCX connector WM5541-ND or similar Square wave will offer the best phase noise performance, but sinusoid is acceptable Power level: 0 to 15dBm Select REF_SMA in clock_config_t

PPS - Pulse Per Second An exteral PPS signal for timestamp synchronization can be supplied by soldering a connector.

Connector J13 (PPS) needs MCX connector WM5541-ND or similar Requires a square wave signal Amplitude: 3.3 to 5Vpp

Test the PPS input with the following app:

<args> are device address arguments (optional if only one USRP is on your machine)

cd <install-path>/share/uhd/examples ./test_pps_input --args=<args>

Internal GPSDO Please see the Internal GPSDO Application Notes for information on configuring and using the internal GPSDO. http://files.ettus.com/uhd_docs/manual/html/gpsdo.html UHD will always try to detect an installed GPSDO at runtime. There is not a special EEPROM value to burn for GPSDO detection.

Hardware setup notes Front panel LEDs The LEDs on the front panel can be useful in debugging hardware and software issues. The LEDs reveal the following about the state of the device:

LED A: transmitting LED B: fpga loaded LED C: receiving LED D: fpga loaded LED E: reference lock LED F: board power

Miscellaneous Available Sensors The following sensors are available; they can be queried through the API.

ref_locked - clock reference locked (internal/external) other sensors are added when the GPSDO is enabled ************************************

UHD - Daughterboard Application Notes Daughterboard Properties The following contains interesting notes about each daughterboard. Eventually, this page will be expanded to list out the full properties of each board as well. Basic RX and and LFRX The Basic RX and LFRX boards have 4 frontends:

Frontend A: real signal on antenna RXA Frontend B: real signal on antenna RXB Frontend AB: quadrature frontend using both antennas (IQ) Frontend BA: quadrature frontend using both antennas (QI)

The boards have no tunable elements or programmable gains. Though the magic of aliasing, you can down-convert signals greater than the Nyquist rate of the ADC. BasicRX Bandwidth (Hz):

For Real-Mode (A or B frontend): 250M For Complex (AB or BA frontend): 500M

LFRX Bandwidth (Hz):


For Real-Mode (A or B frontend): 33M For Complex (AB or BA frontend): 66M

Basic TX and and LFTX The Basic TX and LFTX boards have 4 frontends:

Frontend A: real signal on antenna TXA Frontend B: real signal on antenna TXB Frontend AB: quadrature frontend using both antennas (IQ) Frontend BA: quadrature frontend using both antennas (QI)

The boards have no tunable elements or programmable gains. Though the magic of aliasing, you can up-convert signals greater than the Nyquist rate of the DAC. BasicTX Bandwidth (Hz): 250M

For Real-Mode (A or B frontend): 250M For Complex (AB or BA frontend): 500M

LFTX Bandwidth (Hz): 33M


For Real-Mode (A or B frontend): 33M For Complex (AB or BA frontend): 66M

DBSRX The DBSRX board has 1 quadrature frontend. It defaults to direct conversion, but can use a low IF through lo_offset in uhd::tune_request_t Receive Antennas: J3

Frontend 0: Complex baseband signal from antenna J3

The board has no user selectable antenna setting Receive Gains:


GC1, Range: 0-56dB GC2, Range: 0-24dB

Bandwidth (Hz): 8M-66M Sensors:

lo_locked: boolean for LO lock state

DBSRX2 The DBSRX2 board has 1 quadrature frontend. It defaults to direct conversion, but can use a low IF through lo_offset in uhd::tune_request_t Receive Antennas: J3

Frontend 0: Complex baseband signal from antenna J3

The board has no user selectable antenna setting Receive Gains:


GC1, Range: 0-73dB BBG, Range: 0-15dB

Bandwidth (Hz): 8M-80M Sensors:

lo_locked: boolean for LO lock state

RFX Series The RFX Series boards have 2 quadrature frontends, one transmit, one receive. Transmit defaults to low IF and Receive defaults to direct conversion. The IF can be adjusted through lo_offset in uhd::tune_request_t The RFX Series boards have independent receive and transmit LO's and synthesizers allowing full-duplex operation on different transmit and receive frequencies. Transmit Antennas: TX/RX Receive Antennas: TX/RX or RX2

Frontend 0: Complex baseband signal for selected antenna

The user may set the receive antenna to be TX/RX or RX2. However, when using an RFX board in full-duplex mode, the receive antenna will always be set to RX2, regardless of the settings.

Receive Gains: PGA0, Range: 0-70dB (except RFX400 range is 0-45dB) Bandwidths (Hz):

RX: 40M TX: 40M

Sensors:

lo_locked: boolean for LO lock state rssi: float for rssi in dBm

XCVR 2450 The XCVR2450 has 2 quadrature frontends, one transmit, one receive. Transmit and Receive default to direct conversion but can be used in low IF mode through lo_offset in uhd::tune_request_t The XCVR2450 has a non-contiguous tuning range consisting of a high band (4.9-6.0GHz) and a low band (2.4-2.5GHz). Transmit Antennas: J1 or J2 Receive Antennas: J1 or J2

Frontend 0: Complex baseband signal for selected antenna

The XCVR2450 uses a common LO for both receive and transmit. Even though the API allows the RX and TX LOs to be individually set, a change of one LO setting will be reflected in the other LO setting. The XCVR2450 does not support full-duplex mode, attempting to operate in full-duplex will result in transmit-only operation. Transmit Gains:

VGA, Range: 0-30dB BB, Range: 0-5dB

Receive Gains:

LNA, Range: 0-30.5dB VGA, Range: 0-62dB

Bandwidths (Hz):

RX: 15M, 19M, 28M, 36M; (each +-0, 5, or 10%) TX: 24M, 36M, 48M

Sensors:

lo_locked: boolean for LO lock state rssi: float for rssi in dBm

WBX Series The WBX Series boards have 2 quadrature frontends, one transmit, one receive. Transmit and Receive default to direct conversion but can be used in low IF mode through lo_offset in uhd::tune_request_t The WBX Series boards have independent receive and transmit LO's and synthesizers allowing full-duplex operation on different transmit and receive frequencies. Transmit Antennas: TX/RX Receive Antennas: TX/RX or RX2

Frontend 0: Complex baseband signal for selected antenna

The user may set the receive antenna to be TX/RX or RX2. However, when using an WBX board in full-duplex mode, the receive antenna will always be set to RX2, regardless of the settings. Transmit Gains: PGA0, Range: 0-25dB Receive Gains: PGA0, Range: 0-31.5dB Bandwidths (Hz):

RX: 40M TX: 40M

Sensors:

lo_locked: boolean for LO lock state

SBX Series The SBX Series boards have 2 quadrature frontends, one transmit, one receive. Transmit and Receive default to direct conversion but can be used in low IF mode through lo_offset in uhd::tune_request_t

The SBX Series boards have independent receive and transmit LO's and synthesizers allowing full-duplex operation on different transmit and receive frequencies. Transmit Antennas: TX/RX Receive Antennas: TX/RX or RX2

Frontend 0: Complex baseband signal for selected antenna

The user may set the receive antenna to be TX/RX or RX2. However, when using an SBX board in full-duplex mode, the receive antenna will always be set to RX2, regardless of the settings. Transmit Gains: PGA0, Range: 0-31.5dB Receive Gains: PGA0, Range: 0-31.5dB Bandwidths (Hz):

RX: 40M TX: 40M

Sensors:

lo_locked: boolean for LO lock state

LEDs:

All LEDs flash when dboard control is initialized TX LD: Transmit Synthesizer Lock Detect TX/RX: Receiver on TX/RX antenna port (No TX) RX LD: Receive Synthesizer Lock Detect RX1/RX2: Receiver on RX2 antenna port

TVRX The TVRX board has 1 real-mode frontend. It is operated at a low IF. Receive Antennas: RX

Frontend 0: real-mode baseband signal from antenna RX

Receive Gains:

RF, Range: -13.3-50.3dB (frequency-dependent) IF, Range: -1.5-32.5dB

Bandwidth: 6MHz TVRX2 The TVRX2 board has 2 real-mode frontends. It is operated at a low IF. Receive Frontends:

Frontend RX1: real-mode baseband from antenna J100 Frontend RX2: real-mode baseband from antenna J140

Note: The TVRX2 has always-on AGC, the software controllable gain is the final gain stage which controls the AGC set-point for output to ADC. Receive Gains:

IF, Range: 0.0-30.0dB

Bandwidth: 1.7MHz, 6MHz, 7MHz, 8MHz, 10MHz Sensors:


lo_locked: boolean for LO lock state rssi: float for measured RSSI in dBm temperature: float for measured temperature in degC

Daughterboard Modifications Sometimes, daughterboards will require modification to work on certain frequencies or to work with certain hardware. Modification usually involves moving/removing a SMT component and burning a new daughterboard id into the eeprom. DBSRX - Mod Due to different clocking capabilities, the DBSRX will require modifications to operate on a non-USRP1 motherboard. On a USRP1 motherboard, a divided clock is provided from an FPGA pin because the standard daughterboard clock lines cannot provided a divided clock. However, on other USRP motherboards, the divided clock is provided over the standard daughterboard clock lines. Step 1: Move the clock configuration resistor Remove R193 (which is 10 ohms, 0603 size) and put it on R194, which is empty. This is made somewhat more complicated by the fact that the silkscreen is not clear in that area. R193 is on the back, immediately below the large beige connector, J2. R194 is just below, and to the left of

R193. The silkscreen for R193 is ok, but for R194, it is upside down, and partially cut off. If you lose R193, you can use anything from 0 to 10 ohms there. Step 2: Burn a new daughterboard id into the EEPROM With the daughterboard plugged-in, run the following commands: cd <install-path>/share/uhd/utils ./usrp_burn_db_eeprom --id=0x000d --unit=RX --args=<args> --slot=<slot>

<args> are device address arguments (optional if only one USRP is on your machine) <slot> is the name of the daughterboard slot (optional if the USRP has only one slot)

RFX - Mod Older RFX boards require modifications to use the motherboard oscillator. If this is the case, UHD will print a warning about the modification. Please follow the modification procedures below: Step 1: Disable the daughterboard clocks Move R64 to R84, Move R142 to R153 Step 2: Connect the motherboard blocks Move R35 to R36, Move R117 to R115 These are all 0-ohm, so if you lose one, just short across the appropriate pads Step 3: Burn the appropriate daughterboard id into the EEPROM With the daughterboard plugged-in, run the following commands: cd <install-path>/share/uhd/utils ./usrp_burn_db_eeprom --id=<rx_id> --unit=RX --args=<args> --slot=<slot> ./usrp_burn_db_eeprom --id=<tx_id> --unit=TX --args=<args> --slot=<slot>

<rx_id> choose the appropriate RX ID for your daughterboard o RFX400: 0x0024 o RFX900: 0x0025 o RFX1800: 0x0034 o RFX1200: 0x0026 o RFX2400: 0x0027 <tx_id> choose the appropriate TX ID for your daughterboard o RFX400: 0x0028 o RFX900: 0x0029 o RFX1800: 0x0035

RFX1200: 0x002a RFX2400: 0x002b <args> are device address arguments (optional if only one USRP is on your machine) <slot> is the name of the daughterboard slot (optional if the USRP has only one slot)
o o

UHD - Synchronization Application Notes The following application notes explain how to synchronize multiple USRPs with the goal of transmitting or receiving time-aligned samples for MIMO or other applications requiring multiple USRPs operating synchronously. Note: The following synchronization notes do not apply to USRP1, which does not support the advanced features available in newer products. Common reference signals USRPs take two reference signals in order to synchronize clocks and time:

A 10MHz reference to provide a single frequency reference for both devices, and A pulse-per-second (1PPS) to synchronize the sample time across devices.

Provide reference signals USRPs have two primary means of providing synchronization: Method 1: Connect the front panel SMA connectors to the reference sources. Typically, these signals are provided by an external GPSDO. However, some USRP models can provide these signals from an optional internal GPSDO. Method 2: Use the MIMO Expansion cable to share reference sources (USRP2 and N-Series). The MIMO cable can be used synchronize one device to another device. Users of the MIMO cable may use method 1 to synchronize multiple pairs of devices. Note: For users generating their own signals for the external SMA connectors, the pulse-persecond should be clocked from the 10MHz reference. See the application notes for your device for specific signal requirements. Set the clock configuration In order to synchronize to an external clock, configure the USRP device using the "external" clock configuration: usrp->set_clock_config(uhd::clock_config_t::external());

Sometimes the delay on the PPS signal will cause it to arrive inside the timing margin the FPGA sampling clock, causing PPS edges to be separated by less or more than 100million cycles of the FPGA clock. If this is the case, you can change the edge reference of the PPS clock with the clock_config_t: uhd::clock_config_t clock_config = uhd::clock_config_t::external(); clock_config.pps_polarity = uhd::clock_config_t::PPS_NEG; usrp->set_clock_config(clock_config);

Synchronizing the device time The purpose of the PPS signal is to synchronously latch a time into the device. You can use the set_time_next_pps(...) function to either initialize the sample time to 0, or to an absolute time such as GPS time or UTC time. For the purposes of synchronizing devices, it doesn't matter what time you initialize to when using set_time_next_pps(...). Method 1 - poll the USRP time registers One way to initialize the PPS edge is to poll the "last PPS" time from the USRP device. When the last PPS time increments, the user can determine that a PPS has occurred: const uhd::time_spec_t last_pps_time = usrp->get_time_last_pps(); while (last_pps_time == usrp->get_time_last_pps()){ //sleep 100 milliseconds (give or take) } usrp->set_time_next_pps(uhd::time_spec_t(0.0)); Method 2 - query the GPSDO for seconds Most GPSDO can be configured to output a NMEA string over the serial port once every PPS. The user can wait for this string to determine the PPS edge, and the user can also parse this string to determine GPS time: //call user's function to wait for NMEA message... usrp->set_time_next_pps(uhd::time_spec_t(0.0)); -- OR -//call user's function to wait for NMEA message... //call user's function to parse the NMEA message... usrp->set_time_next_pps(uhd::time_spec_t(gps_time+1));

Method 3 - internal GPSDO USRPs with internal GPSDOs properly configured will automatically configure themselves to set the VITA time to current UTC time. See the GPSDO Application Notes for more details. Method 4 - MIMO cable A USRP can synchronize its time to another USRP via the MIMO cable. Unlike the other methods, this does not use a real "pulse per second". Rather, the USRP sends an encoded time message over the MIMO cable. The slave device will automatically synchronize to the time on the master device. See the MIMO Cable Application Notes for more detail.

Synchronizing channel phase Align CORDICs in the DSP In order to achieve phase alignment between USRPs, the CORDICS in both devices must be aligned with respect to each other. This is easily achieved by issuing stream commands with a time spec property, which instructs the streaming to begin at a specified time. Since the devices are already synchronized via the 10MHz and PPS inputs, the streaming will start at exactly the same time on both devices. The CORDICs are reset at each start-of-burst command, so users should ensure that every start-of-burst also has a time spec set. For receive, a burst is started when the user issues a stream command. This stream command should have a time spec set: uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE); stream_cmd.num_samps = samps_to_recv; stream_cmd.stream_now = false; stream_cmd.time_spec = time_to_recv; usrp->issue_stream_cmd(stream_cmd); For transmit, a burst is started when the user calls send(). The metadata should have a time spec and start of burst set: uhd::tx_metadata_t md; md.start_of_burst = true; md.end_of_burst = false; md.has_time_spec = true;

md.time_spec = time_to_send; //send a single packet size_t num_tx_samps = usrp->get_device()->send( buffs, samps_to_send, md, uhd::io_type_t::COMPLEX_FLOAT32, uhd::device::SEND_MODE_ONE_PACKET, timeout ); Align LOs in the front-end After tuning the RF front-ends, each local oscillator may have a random phase offset due to the dividers in the VCO/PLL chains. This offset will remain constant after the device has been initialized, and will remain constant until the device is closed or re-tuned. This phase offset is typically removed by the user in MIMO applications, using a training sequence to estimate the offset. It will be necessary to re-align the LOs after each tune command. ***************************************

UHD - Internal GPSDO Application Notes


This application note describes the use of integrated GPS-disciplined oscillators with Ettus Research USRP devices. It pertains specifically to the Jackson Labs Firefly-1A device unless noted otherwise. Specifications

Receiver type: 50 channel with WAAS, EGNOS, MSAS 10MHz ADEV: 1e-11 over >24h 1PPS RMS jitter: <50ns 1-sigma Holdover: <11us over 3h Phase noise: o 1Hz: -80dBc/Hz o 10Hz: -110dBc/Hz o 100Hz: -135dBc/Hz o 1kHz: -145dBc/Hz o 10kHz: <-145dBc/Hz

Antenna Types: The GPSDO is capable of supplying a 3V for active GPS antennas or supporting passive antennas Installation instructions

Installation instructions can be found here: www.ettus.com/downloads/gpsdo-kit.pdf Post installation task (N-Series only) This is necessary if you require absolute GPS time in your application, or need to communicate with the GPSDO to obtain location, satellite info, etc. If you only require 10MHz and PPS signals for reference or MIMO use, (see the Synchronization Application Notes), it is not necessary to perform this step. To configure the USRP to communicate with the GPSDO, use the usrp_burn_mb_eeprom utility: cd <install-path>/share/uhd/utils ./usrp_burn_mb_eeprom --args=<optional device args> --key=gpsdo --val=internal -- restore original setting -./usrp_burn_mb_eeprom --args=<optional device args> --key=gpsdo --val=none Using the GPSDO in your application By default, if a GPSDO is detected at startup, the USRP will be configured to use it as a frequency and time reference. The internal VITA timestamp will be initialized to the GPS time, and the internal oscillator will be phase-locked to the 10MHz GPSDO reference. If the GPSDO is not locked to satellites, the VITA time will not be initialized. GPS data is obtained through the mboard_sensors interface. To retrieve the current GPS time, use the "gps_time" sensor: usrp->get_mboard_sensor("gps_time"); The returned value will be the current epoch time, in seconds since January 1, 1970. This value is readily converted into human-readable format using the time.h library in C, boost::posix_time in C++, etc. Other information can be fetched as well. You can query the lock status with the "gps_locked" sensor, as well as obtain raw NMEA sentences using the "gps_gpgsa", "gps_gprmc", and "gps_gpgga" sensors. Location information can be parsed out of the "gps_gpgga" sensor by using gpsd or another NMEA parser. *****************************************

UHD - Calibration Application Notes


Self-calibration The UHD comes with several self-calibration utilities for minimizing IQ imbalance and DC offset. These utilities perform calibration sweeps using transmit leakage into the receive path (special equipment is not required). The results from a calibration are written to a csv file in the user's home directory. UHD will automatically apply corrections at runtime when the user changes settings. Calibration results are specific to an individual RF board. UHD comes with the following calibration utilities:

uhd_cal_rx_iq_balance: - mimimizes RX IQ imbalance vs LO frequency uhd_cal_tx_dc_offset: - mimimizes TX DC offset vs LO frequency uhd_cal_tx_iq_balance: - mimimizes TX IQ imbalance vs LO frequency

The following RF frontends are supported by the self-calibration utilities:


WBX transceiver board SBX transceiver board more to come...

Calibration utilities UHD installs the calibration utilities into <install-path>/bin. Disconnect any extrernal hardware from the RF antenna ports, and run the following from the command line. Each utility will take several minutes to complete. uhd_cal_rx_iq_balance --verbose --args=<optional device args> uhd_cal_tx_iq_balance --verbose --args=<optional device args> uhd_cal_tx_dc_offset --verbose --args=<optional device args> See the output given by --help for more advanced options, such as: manually choosing the frequency range and step size for the sweeps. Calibration data Calibration files are stored in the user's home/application directory. They can easily be moved from machine to another by copying the "cal" directory. Re-running a calibration utility will replace the existing calibration file. The old calibration file will be renamed so it may be recovered by the user.

Unix: ${HOME}/.uhd/cal/ Windows: %APPDATA%\.uhd\cal\

API Documentation
Doxygen : refer to http://files.ettus.com/uhd_docs/doxygen/html/files.html

UHD - Coding to the API Various API interfaces Low-Level: The device API A device is an abstraction for hardware that is connected to the host system. For a USRP, this means that the motherboard and everything on it would be considered to be a "device". The device API provides ways to:

Discover devices that are physically connected to the host system. Create a device object for a particular device identified by address. Register a device driver into the discovery and factory sub-system. Streaming samples with metadata into and out of the device. Set and get properties on the device object.

See the documentation in device.hpp for reference. High-Level: The multi usrp The Multi-USRP class provides a fat interface to a single USRP with one or more channels, or multiple USRPs in a homogeneous setup. See the documentation in usrp/multi_usrp.hpp for reference.

********************************

UHD - Device streaming Introduction to streaming The concept of streaming refers to the transportation of samples between host and device. A stream is an object that facilitates streaming between host application and device. A RX stream allows the user to receive samples from the device. A TX stream allows the user to transmit samples to the device.

Link layer encapsulation The VITA49 standard provides encapsulation for sample data across a link layer. On all generation2 hardware, samples are encapsulated into VRT IF data packets. These packets also provide sample decoration such as stream time and burst flags. Sample decoration is exposed to the user in the form of RX and TX metadata structs. The length of an IF data packet can be limited by several factors:

MTU of the link layer - network card, network switch Buffering on the host - frame size in a ring buffer Buffering on the device - size of BRAM FIFOs

Data types There are two important data types to consider when streaming:

The data type of the samples used on the host for processing The data type of the samples sent through the link-layer

The host/CPU data type The host data type refers to the format of samples used in the host for baseband processing. Typically, the data type is complex baseband such as normalized complex-float32 or complexint16.

The link-layer data type The link-layer or "over-the-wire" data type refers to the format of the samples sent through the link. Typically, this data type is complex-int16. However, To increase throughput over the linklayer, at the expense of precision, complex-int8 may be used. Conversion The user may request arbitrary combinations of host and link data types; however, not all combinations are supported. The user may register custom data type formats and conversion routines. See uhd/convert.hpp for futher documentation. TODO provide example of convert API *****************************************

Gnuradio + UHD
The easiest way to compile and install UHD + Gnuradio from source if you are using Ubuntu or Fedora Linux is to use the build-gnuradio script thats already explained .

You can also build gnuradio in MSVC following this guide: CMakeWork The goal here is to build gnuradio under various systems using CMake. Install the dependencies UNIX dependencies

Install CMake through your OS's package manager or by some other means. Follow the OS specific instructions to install other dependencies:

Windows dependencies Dependenc y Purpose Notes Choose install option: Add to PATH URL

git

checkout source code

http://code.google.com/p/msysgit/

cmake

Choose install build system option: Add to PATH all libraries Build lib/dll with project file

http://www.cmake.org/cmake/resources/software.html

boost

http://www.boostpro.com/download/

cppunit

C++ unit tests

http://gaiacrtn.free.fr/cppunit/index.html

fftw

gnuradiocore

Manually generate http://www.fftw.org/install/windows.html .lib from .def Manually generate http://gnuwin32.sourceforge.net/packages/gsl.htm .lib from .def

gsl

gnuradiocore

swig

python wrapped blocks build system Use 2.6 or 2.7

http://www.swig.org/download.html

python

http://www.python.org/download/

SDL

video-sdl component qtgui component qtgui component qtgui component qtgui component many components

http://www.libsdl.org/download-1.2.php

qt

http://qt.nokia.com/downloads/ Follow READM http://sourceforge.net/projects/qwt/ E to build http://www.riverbankcomputing.co.uk/software/pyqt/down load http://pyqwt.sourceforge.net/download.html

qwt

pyqt

pyqwt

numpy

http://sourceforge.net/projects/numpy/files/NumPy/ easy install.ex http://pypi.python.org/pypi/setuptools e Cheetah lxml Use the all-in-one http://www.pygtk.org/downloads.html installer

setuptools

gnuradio companion

pygtk

gnuradio companion generated documentatio n

doxygen

http://www.stack.nl/~dimitri/doxygen/download.html

Get the source code The master branch of gnuradio.git has cmake support: http://gnuradio.org/redmine/projects/gnuradio/wiki/Download

Configure the build UNIX configuration mkdir <gnuradio build directory> cd <gnuradio build directory> cmake <gnuradio source directory> -- OR -cmake-gui <gnuradio source directory> Windows configuration

Open the CMake GUI from the start menu Specify the source and binary directories Now the following is an iterative process: o Click configure o Enter parameters o Repeat until all desired components are enabled Click generate

A screen-shot of a configured gnuradio build: http://i.imgur.com/8qXWb.png Component selection By default, the build system will enable all components that it can find dependencies for. Use cmake-gui or ccmake (curses) to graphically enable or disable components. Or follow the examples below to configure via the command line: Disable some components: cmake -DENABLE_GR_AUDIO=OFF <gnuradio source directory> Disable all components by default and manually enable desired components:
cmake -DENABLE_DEFAULT=OFF -DENABLE_GRUEL=ON -DENABLE_GR_CORE=ON <gnuradio source directory>

Cause configure to error when an enabled component does not meet dependencies: cmake -DENABLE_GR_QTGUI=FORCE <gnuradio source directory>

Build the source CMake has generated a build environment depending upon your system type and the generator : http://www.cmake.org/cmake/help/cmake-2-8-docs.html#section_Generators options passed into CMake. Below is some documentation for the using the most common build environments (Makefiles on UNIX, and MSVC on Windows): Makefiles Open a terminal and enter the following commands: cd <gnuradio build directory> make make test sudo make install sudo ldconfig MSVC command prompt Open the Visual Studio command prompt and enter the following commands: cd <gnuradio build directory> devenv gnuradio.sln /build Release /project ALL_BUILD devenv gnuradio.sln /build Release /project RUN_TESTS devenv gnuradio.sln /build Release /project INSTALL MSVC GUI

Open <gnuradio build directory>\gnuradio.sln in Visual Studio Set the build type to Release Right click on the "ALL_BUILD" target and select Build Right click on the "RUN_TESTS" target and select Build Right click on the "INSTALL" target and select Build

Post-installation tasks In general, you need to set the bin path, the library path, and the python path for your new gnuradio installation. UNIX post-installation Follow the OS specific instructions to setup install paths: BuildGuide: http://gnuradio.org/redmine/projects/gnuradio/wiki/BuildGuide#Operating-System-SpecificInstructions

Windows post-installation You need to set the PATH and PYTHONPATH path environment variables. I recommend using Rapid Environment Editor: http://www.rapidee.com/en/about

Set the PATH to include <gnuradio install directory>/bin Set the PYTHONPATH to include <gnuradio install directory>/lib/site-packages Add the dlls from all dependency libraries into the PATH or copy them into <gnuradio install directory>/bin

To compile and install by hand:


Get Gnuradio source with UHD support (gr-uhd blocks) from the "master" branch in the Gnuradio git repository: git clone http://gnuradio.org/git/gnuradio.git o The Gnuradio git repository can be browsed on the web with cgit here: http://gnuradio.org/cgit/gnuradio.git/log/ o Follow the Gnuradio build guide o Check your dependencies o After "./configure" in the Gnuradio source tree, make sure that gr-uhd is one of the enabled components. o Continue with to build and install as usual.

Asterisk
Installing and Configuring Asterisk Asterisk is the standard open-source PBX solution. Installing Standard Asterisk There are numerous existing pages online detailing the specifics of this complex piece of software. This page(http://www.voip-info.org/wiki/view/Asterisk+installation+tips ), for instance, details the process for installing Asterisk on numerous different platforms. For most simple installs, we suggest just installing Asterisk from the main software repository. On Ubuntu: sudo apt-get install asterisk Configuring Asterisk Standard asterisk does not not need any configuration to handle calls; they all come into an external context. For higher level-functions (e.g., routing), you may need to install hooks into the subscriber registry. to get more information about how to install and use asterisk refer to the the document title with name: VoIP Cookbook: Building your own Telecommunication Infrastructure By Onno W. Purbo Anton Raharja

Getting Started With Asterisk


What is Asterisk? Asterisk PBX, from now on just called Asterisk, is Linux based, Open Source and free PBX software. Or to quote from the Asterisk website http://www.asterisk.org (with corrected spelling ;) )

Asterisk is a complete PBX in software. It runs on Linux and provides all of the features you would expect from a PBX and more. Asterisk does voice over IP in three protocols, and can interoperate with almost all standards-based telephony equipment using comparatively inexpensive hardware.

Asterisk provides Voicemail services with Directory, Call Conferencing, Interactive Voice Response, Call Queuing. It has support for three-way calling, caller ID services, ADSI, SIP and H.323 (as both client and gateway). Check the Features section for a more complete list.

Asterisk needs no additional hardware for Voice over IP. For interconnection with digital and analog telephony equipment, Asterisk supports a number of hardware devices, most notably all of the hardware manufactured by Asterisk's sponsors, Digium. Digium has single and quad span T1 and E1 interfaces for interconnection to PRI lines and channel banks. In addition, an analog FXO card is available, and more analog interfaces are in the works.

Also supported are the Internet Line Jack and Internet Phone Jack products from Quicknet.

Asterisk supports a wide range of TDM protocols for the handling and transmission of voice over traditional telephony interfaces. Asterisk supports US and European standard signaling types used in standard business phone systems, allowing it to bridge between next generation voice-data integrated networks and existing infrastructure. Asterisk not only supports traditional phone equipment, it enhances them with additional capabilities.

Using the IAX Voice over IP protocol, Asterisk merges voice and data traffic seamlessly across disparate networks. While using Packet Voice, it is possible to send data such as URL information and images in-line with voice traffic, allowing advanced integration of information.

Asterisk provides a central switching core, with four APIs for modular loading of telephony applications, hardware interfaces, file format handling, and codecs. It allows for transparent switching between all supported interfaces, allowing it to tie together a diverse mixture of telephony systems into a single switching network.

Asterisk is primarily developed on GNU/Linux for x/86. It is known to compile and run on GNU/Linux for PPC. Other platforms and standards based UNIX-like operating systems should be reasonably easy to port for anyone with the time and requisite skill to do so. Asterisk is available in the testing and unstable debian archives, maintained thanks to Mark Purcell.

Who Made Asterisk? Asterisk was originally written by Mark Spencer of Digium dba Linux Support Services, Inc. Code has been contributed from Open Source coders around the world, and testing and bugpatches from the community have provided invaluable aid to the development of this software. markster@digium.com : http://www.digium.com/

Document Conventions Just to clear up any confusion that may occur here are the conventions used in this guide. Text that appears in grey boxes like this contain the text that should be typed in, or output depending on the context; however you should omit the leading # character as this simply represents the shell prompt.

# ls /etc/asterisk

Installing Linux for Asterisk

In order to use Asterisk you are going to have to use Linux. If you are a Linux guru then you might want to skip this section and just take a look at the dependencies. This section deals with installing a Linux system for use with Asterisk. I make no excuses or arguments for the chosen distribution, Red Hat 8; I have no intention of discussing the pros and cons of the many different distributions available. In other words, if you dont like Red Hat, stop bitching and find a windows user to torment.

Getting the ISO images

Im not going to tell you how to create the CDs required to install Linux, there are other sites for this. You can find the ISO images required from places like http://www.linuxiso.org. Download the ISO images and burn them. For This installation you only actually need disks 1, 2 and 3 (the assumption is you are using the default language settings) If you are pushed for a network connection you can get away with only downloading and burning those, however, I would recommend getting the whole set for the sake of completeness.

Installing Linux The first step is to insert CD 1 of your freshly burned ISO images into the target machines CDROM drive and boot. At this stage Im going to make an assumption that you are either installing Asterisk on a new machine or overwriting the disks of whatever was there before. If you want to dual boot into Asterisk, please look elsewhere for initial configurations. You might want to consult your physician too. I make no apologies that this section is going to treat you like a moron; this is intentional. Since we want to be sure that you have no problems running Asterisk we need to make sure that your installation matches the one I used to build and run it. The first thing you will need to do on your target machine is ensure that you can boot directly from CD. Most modern (if not all) will allow this, it is usually just a setting in your BIOS. If you dont feel comfortable with messing in the BIOS the simplest test you can do to check and see if booting from CD is enabled is, funnily enough, to put CD 1 into the drive and reboot the machine. If the machine starts to boot and eventually shows a screen like the one on the following page, then you are ok. If you are happy fiddling with the BIOS then just enable booting from CD and make it the first device to attempt to boot from.

In either case you should have something like this appear on your screen:

At this point all you need to do is press ENTER. After a short while, you will be presented with the following introductory screen:

Click the NEXT button

Select the language you want to use during the installation. Since I used the default on English, all the following screens will also be in English. Then Click NEXT.

Select the keyboard layout for your particular PC. Most keyboards in the English speaking world tend to be U.S. English but check yours.

Since we are not going to be installing a windowing system on this machine, in all honesty we dont care about the mouse. Click NEXT.

Since we are going to build a custom installation select CUSTOM and click NEXT.

This bit might seem a little scary, theres nothing to worry about, since we have already established that we are NOT going to dual boot and there is nothing that we want to keep on the disks in this machine. You did check that right?! Click NEXT.

If you get the previous screen, dont worry too much just click YES. You many note that the message box refers to hda not sda, dont worry about this either, its just the type of disks you are using. If you have IDE disks then this would say hda.

Depending on the state of this machine and the disks before you started this install you can either select Remove all Linux Partitions on this System or Remove all Partitions on this system If the disks have been previously used for another Operating system then select the Remove all partitions on this system option. If your disks are brand new and have not been used before then either of the first two options is fine. The box below these options will list the hard drives available on your system, leave the selections alone. Click the NEXT button. If you chose to remove all partitions on the system you will see the message box on the following page. Again the disk name /dev/sda may and most likely would be /dev/hda

Click YES

You should see the following screen showing how the disks will be laid out, click the NEXT button.

Click NEXT

Now comes the hard part. If you know nothing about your network then we are going to be a little stuck. This is the part that is specific to your installation. I am not going to attempt to explain how networks function, if you have one they you should at least understand the terms in the next couple of paragraphs.

As shown on the screenshot on the previous page, the default for a Red Hat installation is to use DHCP. If you are using a DHCP server on your network then you can click NEXT. If you are not then you will need to click the edit button, then deselect DHCP and enter an IP address and subnet mask for this machine. As a side note most home run networks tend to use the address range 192.168.0.x and a subnet mask of 255.255.255.0 The x being replaced with the individual IP address of a particular machine. You can establish this by looking at one of your other machines, and its configuration settings. Again, generally, the Gateway and DNS are usually going to be something like 192.168.0.1 for both. This is however VERY SPECIFIC to your network. You much make the setting match your existing network. If you are using DHCP then for the hostname you can let DHCP handle it. If not then select manually and type a name for this host.

Again, for a non-DHCP environment fill in the Gateway and Primary DNS fields. Do NOT use the settings in the above screenshot unless they match your network. Once you have done this click NEXT

Select no firewall and click NEXT.

Click NEXT. If you want to use additional languages, select the ones you want first.

Select your location or at least the nearest place to you that is listed and click NEXT.

Enter a password for the root user. If you were unaware, the root user is like the administrator account on a Windows machine, the big boss account.. Use TAB or the mouse to move between the fields. Once youve done that (and remembered the password!) click NEXT.

Click NEXT

Now we have to select the applications that we want to install. The only things you need to select are:

  

Development Tools Kernel Development Text Based Internet (optional but advised)

Make sure you also have Select individual packages selected (see cursor on previous page screenshot). Now click NEXT

Select Flat View and ensure that the following ADDITIONAL items are selected:

OpenSSL-Devel

Readline41 Ncurses4 Ncurses C++ Devel SOX Now click NEXT


Ok, this is it, we are about to do the install, Click NEXT

The first ting youll see is the disks being formatted and partitioned, once complete the various packages will be installed. You will be prompted to insert disks, change the CD, and then click OK.

You dont really need to create a boot disk. Select no and click NEXT.

Do NOT remove the CD, the install will eject it for you, Click EXIT and your machine will reboot. Once complete you will be presented with something like:

You may now dance around the room a little; you have completed the Linux install part of Asterisk Get a coffee, tea, cola or drink of your choice and bask in this glorious moment. Then read the next section on installing Asterisk.

Additional Installs You may also need (depending on your desire to have music on hold) mpg123 which can be found at http://www.mpg123.de/mpg123/mpg123-0.59r.tar.gz From your Linux box you can also type

# cd /usr/src # wget http://www.mpg123.de/mpg123/mpg123-0.59r.tar.gz

Extract it and compile

# tar -zxvf mpg123-0.59r.tar.gz # cd mpg123-0.59r # make linux # make install Once compiled make sure there is a copy in

/usr/bin/mpg123 Note that the copy of mpg123 that comes with Red Hat 8 is of no use to you, it will not work with Asterisk.

Obtaining Asterisk PBX


You can run Asterisk without any of Digium's hardware but unless you have some sort of PSTN gateway/card youll only be making network calls. From the Asterisk website download page: The best way to obtain Asterisk is to check out a fresh copy from the CVS Server. To check out code from our CVS repository: # cd /usr/src # export CVSROOT=:pserver:anoncvs@cvs.digium.com:/usr/cvsroot # cvs login - the password is anoncvs. # cvs checkout zaptel libpri asterisk

This will create four directories, zaptel, libpri, and asterisk. Compiling them is generally quite straightforward. Just change to each directory and type make install, in this order. Compile zaptel, then libpri, and then asterisk. # cd zaptel note if you do not have any Digium hardware and you want to use music on hold etc you may find that you need to modify the Makefile in this directory. Near the end of line 82, change # ztdummy to ztdummy (i.e. remove the #) then continue # make clean ; make install # cd ../libpri # make clean ; make install # cd ../asterisk # make clean ; make install Remember to do a # make samples

to generate the basic configuration files. Hopefully everything compiled ok, you can test that Asterisk will run by typing # asterisk vvvvc And hitting return, you should see screens and screens of information that means nothing to you at all. This doesnt matter at this point, at least Asterisk works! Type STOP NOW

And hit enter in the Asterisk command line, Asterisk will exit.

Adding Digium Cards

Digium sell a number of cards for use with Asterisk, these range from single FXO in the guise of the X100P through to fully fledged quad E/T1 cards. If you are setting up Asterisk at home then an X100P (or two if you have 2 lines) should be enough for your needs. You might also want to get an FXS card so that you can get standard analog phones working with Asterisk. My own configuration at home consists of a single X100P and a dual port TDM20B card TDM400P is the generic name for the card, specific names exist for the number of ports on the card i.e.: TDMx0B where x is either 1, 2, 3 or 4 denoting the number of ports. There are a couple of things to note about the X100P. Although the card should work in your country things like caller id detection may not. In the USA you should have no problems at all, but in Europe/rest of the world you should consider searching the archives for information.

At the time of writing the following countries appear to have either full or rudimentary support for caller id:

USA UK FR/DE RO

Full Not on BT, *SOME* cable companies may work. Just being implemented (patched) Yes (patched)

Those that dont work include: NL/DK (although some preliminary work has been done on these locations and hopefully they will be supported soon) If anyone has any other locations that are known to work/not work please let me know. If you are not going to be adding cards to your system you may want to skip this section to get started, although it is recommended that you read the entire document for completeness. In the machine I use for Asterisk; a Dell Optiplex GX115 I have disabled the soundcard since I do not need it. You may wish to keep it enabled but bear this in mind if you get IRQ conflicts.

X100P Installation I hope I can make the assumption that you are capable of adding a new card to your system, if not get someone who knows what they are doing to help out. Oh and please wear a wrist strap. The X100P card is what we call an FXO (Foreign Exchange Office) card. Unless you know about telecoms then that probably didnt mean much. What it means to you and me is that you can plug a cable into the phone socket on your wall and into the back of the X100P; this is your incoming line from your telecoms provider (KPN/BT/Bell etc). You may have noticed that there are 2 sockets on the back of the X100P; one marked as the line interface and the other as a phone interface. Plug in an appropriate cable between the wall socket and the line interface on the card. If you have a spare phone then plug this into the phone interface on the card too. It is always good to have a phone plugged into this interface because in the event of asterisk failing, or a power cut the card actually still allows access to the PSTN line. Obviously if you decide to use a phone that is not powered from the phone line, if you have a power cut, it will not work.

TDM400P Installation The TDM400P card is an FXS (Foreign Exchange Station) card; its what you plug standard analog phones into to use them with asterisk. For those using phones from the UK you may need an adaptor that provides a ring capacitor to actually get the phone to physically ring. I have both a BT Easicom 1000 and a Panasonic KXTCD-777 (this is a DECT base station and 2 handsets sold in one box). The Panasonic phones do not require the adaptor with ring capacitor but the BT Easicom does. If you are using phones from the USA (aside from any power requirements they may have) you should just be able to plug them in.

Configuration Once the cards have been physically plugged into your Asterisk machine, power it up again. Once youve logged in youll need to configure the cards. Its worth pointing out that you do not have to have one of each card type but this section will make the assumption that you have got one of each so that we can cover a much fuller configuration. The first thing youll need to do is modprobe for the cards, basically this makes your linux system poke the card via its driver modprobe zaptel modprobe wcfxo modprobe wcfxs The order in which you do the modprobes IS important. If you modprobe the FXO (modprobe wcfxo) card first then it will be channel 1, if you modprobe the FXS (modprobe wcfxs) card first then its first port will be channel 1, the second channel 2 and so on Now you need to tell asterisk which ports are for what edit /etc/zaptel.conf # vi /etc/zaptel.conf

Note to exit vi hit the escape key then type : wq to write the file and quit. If you want to quit without saving use q! instead of wq

My zaptel.conf consists of the following fxsks=1 fxoks=2 fxoks=3 loadzone=nl defaultzone=nl

The loadzone and defaultzone are fairly obvious and are simply your ISO country code Not all country codes are available, but to be honest I was running with us for a couple of months here in Holland with no issues.. Note: The first 3 lines are very important so pay attention. Just to confuse you more FXO ports use FXS signaling and FXS ports use FXO signaling. So from the above configuration you can see that port 1 (fxsks=1) is actually an FXO card (X100P) and ports 2 and 3 are on the FXS card (TDM20B). Note that you do not have to have the cards in this order, but they must match the order you modprobed them. Since I have a single port FXO card and a 2 port FXS (with the ability to add 2 more ports) it makes sense to put the FXO card as the first, otherwise Id have to change my configuration files a bit when (if) I added more FXS ports. Save your file and then edit /etc/asterisk/zapata.conf # vi /etc/asterisk/zapata.conf

This is where you set the configuration for each of the channels on the cards (you can think of the channels as lines if you like). Its important to note that the configuration in zapata.conf is what I would call backwards i.e. you set the features for a channel, then you assign the channel to them. There is actually a very good reason for this. We are only dealing with a couple of channels so its not a big deal, but imagine if you were dealing with 128, 256 or more Doing it backwards allows you to set the configuration for all the channels and assign them all at once (making slight modifications if required)

When you edit the file you may see things like [channels] relaxdtmf=yes callwaiting=yes callwaitingcallerid=yes threewaycalling=yes transfer=yes cancallforward=yes usecallerid=yes

these are all pretty specific to your environment, they take either yes or no as the argument. Hopefully what they do is obvious, for example: callwaiting=yes gives you a call waiting tone if you are on the phone and someone else rings. Many of these features need to be supported by your local telco (Bell/BT/KPN..etc) At the bottom of this section are example zaptel and zapata config files that should work immediately if your configuration MATCHES mine i.e. you have 1 X100P and 1 TDM20B. Some of the options available in this configuration file are as follows: More than likely you will want to turn on echo cancellation echocancel=yes echocancelwhenbridged=yes

The gain options allow us to increase or decrease the volume if the devices we have appear to quite or loud to be honest you should not really need to change the rx/tx gain settings under normal circumstances. rxgain=0.0 txgain=0.0

Groups allow us to bundle devices together to act more or less as one, got example in Dial strings you can use g<device-group-number>. A dial string would look something like this: Dial(ZAP/g1/1234567890,60) There is a good reason for this, if for example, you had 10 outgoing lines, you would normally want to dial out on any line that was available, not a specific one. Using the group option will allow asterisk to search for a free line within that group. group=1

Pickup groups allow you to group devices, phones or lines together so that you can pick them up using *8. For example if a phone connected to FXS port 1 rings you may want the phone on FXS port 2 to be able to pick it up. pickupgroup=1-4 The immediate feature is what I like to call theBatphone option. If this is set to yes, when you pick up the line it will automatically dial the s extension for the context this line is in. Think back to the TV show Batman, when Commissioner Gordon was in his office and needed to talk to Batman, he simply picked up the receiver on the red Batphone and it rang in the Batcave. So you see, even super heroes can use asterisk! In this instance its of no real use to us, as we are defining the PSTN line.. immediate=no

The context is the place in extensions.conf that calls on this line will jump to. Its a good idea to identify the 2 types of card in using this. Setting the FXO care to jump to the Bell context when a call comes in context=bell

As I said before, FXO devices use FXS signaling so we need to set that here too, it needs to match what you had in your zaptel.conf file BUT, and the reson is unknown to me, instead of fxsks we need to use fxs_ks. There are of course other signaling methods (see the draft manual for all the options) signalling=fxs_ks If we have callerid we can pass it on to asterisks extension logic callerid=asreceived All the settings above have not been assigned to a channel yet, so we do that next channel=1 Its worth noting that all the values (above the channel=1) now become the default values for all other channels, this means you only need to change those you want and all others will be taken from above. context=home group=2 signalling=fxo_ks mailbox=2468 ; you will need to create this mailbox! callerid="Phone 1" <2468> channel=2 signalling=fxo_ks mailbox=3579 ; you will need to create this mailbox! callerid="Phone 2" <3579> channel=3 So, finally we have the zapata and zaptel config files complete, they should look similar to this: /etc/zaptel.conf fxsks=1 fxoks=2 fxoks=3 loadzone=nl defaultzone=nl

/etc/asterisk/zapata.conf [channels] busydetect=1 busycount=7 relaxdtmf=yes callwaiting=yes callwaitingcallerid=yes threewaycalling=yes transfer=yes cancallforward=yes usecallerid=yes echocancel=yes echocancelwhenbridged=yes rxgain=0.0 txgain=0.0 group=1 pickupgroup=1-4 immediate=no context=bell signalling=fxs_ks callerid=asreceived channel=1 context=home group=2 signalling=fxo_ks mailbox=2468 callerid="Phone 1" <2468> channel=2 signalling=fxo_ks mailbox=3579 callerid="Phone 2" <3579>

channel=3 You will need to restart asterisk completely if you make changes to these files at a later date. At this point we can also run ztcfg with vv ( v v not w) [root@ASTERISK asterisk]# ztcfg -vv Zaptel Configuration ====================== Channel map: Channel 01: FXS Kewlstart (Default) (Slaves: 01) Channel 02: FXO Kewlstart (Default) (Slaves: 02) Channel 03: FXO Kewlstart (Default) (Slaves: 03) 3 channels configured.

The next stage is to modify our extensions.conf to configure the numbers for the cards

Setting up SIP
The configuration files for Asterisk are stored in /etc/asterisk so go there:

# cd /etc/asterisk the files we are particularly interested in are sip.conf and extensions.conf. The first thing we will need to do is edit sip.conf - Use whichever editor you are familiar with under Linux - I use vi. Note to exit vi hit the escape key then type : wq to write the file and quit. If you want to quit without saving use q instead of wq

# vi sip.conf If you've ever looked at a windows .ini file you'll notice the format is very similar. In the [general] section you need to add a line to register asterisk with your sip proxy (eg ix66), you should end up with something like the example below. [general] port = 5060 ; Port to bind to bindaddr = 0.0.0.0 ; Address to bind to context = sip ;default Default for incoming calls

An important point here, if you do not have a sip aware firewall and are just using port forwarding then ensure that your context points to somewhere like invalidcalls. If you do not do this then someone could call one of your extensions direct from the Internet. If you had an FXO card in the machine, this could lead to them being able to make PSTN calls!! register => me@mysipproxy.com/1000

A couple of things to note here, obviously the sip address "me@mysipproxy.com" is one that someone would normally call you on. The /1000 at the end of the 'register =>' line is actually the extension that asterisk will use for this address, ie when someone calls me@mysipproxy.com extension 1000 will ring. If you re registering with FreeworldDialup then you will need to add your password to the register line too: e.g.

register => 21103:mypassword@fwd.pulver.com/1000 You now need a section to define the proxy information: [mysipproxy.com] type=peer host=192.168.72.2 fromuser=andy secret=mypassword fromdomain=mysipproxy.com

That part is fairly straight forward using these guidelines:

[section name] - the section name is the bit after the @ in your 'register =>' line

type =

- this is a peer.

host=

- the ip address of the ASTERISK server.

fromuser

- username used for registration

secret - password for this account if required, if no password is required comment it out using a ; in front

fromdomain

- the domain that the username is from.

For FreeworldDialup use

[fwd.pulver.com] type=friend secret=mypassword username=my fwd number host=fwd.pulver.com We now need to define a couple of phones. I use Snom 100's, but you may just want to use sjphone (http://www.sjlabs.com) or something like that. [phone1] type=friend host=dynamic defaultip=192.168.1.4 ;username=blah ;secret=blah dtmfmode=rfc2833 ; Choices are inband, rfc2833, or info mailbox=1000 ; Mailbox for message waiting indicator context=sip callerid="Me" <2124> [phone2] type=friend ;secret=blah host=dynamic defaultip=192.168.1.3 dtmfmode=rfc2833 ; Choices are inband, rfc2833, or info mailbox=1000 ; Mailbox for message waiting indicator context=sip callerid="Mini Me" <2123>

Since the configuration for both phones will be similar I'll only deal with 'phone1'. First of all the [phone1] is important, it's what you will use in your extensions file to identify this physical phone when issuing Dial commands. (e.g. Dial(SIP/phone1,20,tr) - we'll get to this later).

The type= is going to be a friend in this instance, peer is used when Asterisk is contacting a proxy, user is used for phones that can only make calls, and friend acts as both a peer and a user. Set your host=dynamic and the IP address in the defaultip= entry too. If your host has an entry in your DNS then you just enter the machines name in the host= field. Unless you have a good reason to leaving it as dynamic and using the IP given to the phone (fixed or DHCP allocated) is perfectly ok. The username and secret fields are only used when the username is not the same as the client. You should be able to safely ignore this for the moment. dtmfmode= is somewhat trial and error, it depends on your physical phone or software, I've found that my Snom 100's need rfc2833 for DTMF tones to be heard, and SJphone needs inband. Essentially it's trial and error, but once you establish which is needed for what type of phone, it applies to all. This should not be installation specific, ie I've just told you that Snom 100's use rfc2833, so you can use those too..(for the Snoms also change the phone config. mailbox= is the voicemail mailbox that is checked for messages, this information is then passed to the phone, on a Snom 100 phone it results in an envelope icon. Usually you'll have more than one mailbox, one for each user or extension. context= is extremely important you should, in the first instance make this the same for all your sip clients. If a phone is not in a a valid context you will not be able to use it. I've used 'sip' you can use whatever you like, but make sure they are the same, you will need to make an entry in your extensions.conf file (which we will get to later) callerid= is pretty self explanatory, however, note that the callerid must be in the format above, ie "text" <number> it's the whole line that's the callerid, not just the bit in quotes. Essentially the name goes in the quotes and the number between the < and >. Once you've set up these phones you'll need to add some information in your extensions.conf file:

# vi extensions.conf

You'll see there is a lot of information here, for the moment ignore this. Go to the bottom of the file and add [sip] and press return. This needs to be the same as the context= section for your phones defined in sip.conf surrounded by square brackets. If I had set the context= to wibble (context=wibble) then this section would be called [wibble].

Next we'll add a couple of extensions for the phones defined in sip.conf

exten => 1,1,Dial(SIP/phone1,20,tr) exten => 2,1,Dial(SIP/phone2,20,tr) exten => 1000,1,Dial(SIP/phone1&SIP/phone2,20,tr) Add the above lines in the [sip] section. The format of the exten lines is fairly simple:

exten => extension number, command priority, command

Since an extension may have a number of commands there may be multiple entries for an exten. We'll do some more complex stuff later but for the moment save this file. When you start asterisk without any parameters it runs as a daemon. Enter the following command: # asterisk If you get the error ERROR[8192]: File asterisk.c, Line 1249 (main): Asterisk already running on /var/run/asterisk.ctl. Use 'asterisk -r' to connect. then asterisk is already running and you should use the command

# asterisk r to connect to the daemon, adding vvvvvvvvvgc to this will give us debug information too ie: # asterisk vvvvvvvgrc

If the daemon was running and you got the error type

reload

and hit enter at the prompt. If you did not get the error you do not need to do anything, however you might want to attach to the daemon anyway using.

# asterisk vvvvvvvgrc You will need to configure your phones to connect to the asterisk machine. This varies from device to device here is an example for Snom phones: Under Home > Settings > SIP > Lines Add the Name as phone1, the Account as phone1 and the Registrar as the IP of your asterisk pbx and click save. Do the same for your second phone, replacing 'phone1' with 'phone2'.You should now have 2 phones registered to asterisk (it may take a few seconds to actually happen). If you like you can check by typing:

sip show peers from the asterisk console, this should result is a display a little like the one below Name/username Host Mask Port Status phone1/phone1 192.168.1.4 (D) 255.255.255.255 5060 Unmonitored phone2/phone2 192.168.1.3 (D) 255.255.255.255 5060 Unmonitored Go to 'phone1' and dial '2', phone2 should start ringing. If not double check everything. If it does, hang up and then go to phone2 and dial '1'. phone1 should start ringing. When someone calls the address in your sip.conf (eg me@mysipproxy.com) both phones should ring. Of course all this is wonderful if you only want to talk internally, but how can you talk to other people over

the internet? If you've registered with a proxy for example FreeworldDialup add an entry like this:

[fwd] exten => _8.,1,Dial,SIP/${EXTEN-1}@fwd.pulver.com,tr Next add include => fwd in the [sip] section of your extensions.conf. This will allow you to dial 8 then the users FreeworldDialup number e.g. 8100001 would dial FWD's voicemail. On hard phones, this is much easier than having to type a full sip address. Got some friends you call often over the internet? just set up an exten line for them:

exten => 4002,1,Dial,SIP/keith@his-sip-address.com Now you just dial 4002 and it will call them...

Voicemail - Please leave a message after the tone...


Ok, so you've got the basics going, and it's great - if you happen to sit by you phone all the time. What happens if you are out/away from your desk/sleeping you'll miss those vital calls. We need to set up voicemail to capture all those messages if we miss them. The first thing we need to do is create the mailbox for Asterisk to use, thankfully there is a little utility to do this:

# /usr/src/asterisk/addmailbox

You'll be prompted for a mailbox number, Enter mailbox number:

for now enter 9999 and hit return. This will copy a number of files required for the mailbox. Voicemail files can be found in

/var/spool/asterisk/vm/ each mailbox has is a subdirectory from this point, so mailbox 9999 is

/var/spool/asterisk/vm/9999/ You don't really need to worry about these files, but at least you now know where they are on your system. The next thing we need to do is modify a few files so that the mailbox can be used. We need to edit the config files, so go to their location: # cd /etc/asterisk The first of the files we are interested in is voicemail.conf, edit the file # vi voicemail.conf The section we are interested in is [default]. If, which is likely, you have the sample configs installed then you will see a number of entries in this file. You can comment them out if you like by placing a semi-colon ';' in front of the line. [default] ;1234 => 4242,Example Mailbox,root@localhost

Add the line 9999 => 1234,<your name in here>,<your email address here> The format of the file is pretty simple:

mailbox number => mailbox password, mailbox description, mailbox user email address Once you have added the line for the 9999 mailbox, save the file. Next we'll need to edit out sip.conf to make sure that the phones we set up earlier are going to use the correct mailbox for notification.

# vi sip.conf find the entries for [phone1] and [phone2] and change the lines that read:

mailbox=1000 ; Mailbox for message waiting indicator to read mailbox=9999 ; Mailbox for message waiting indicator Note that this will be of most use if your phones support either a message waiting indicator of some sort. Save the file. For the moment we are going to use the same mailbox for both phones, but you can set up one for each if you like. Now edit your extensions.conf file # vi extensions.conf

locate the [sip] section where you added the entries for your extensions earlier in this document, the lines should look similar to these:

exten => 1,1,Dial(SIP/phone1,20,tr) exten => 2,1,Dial(SIP/phone2,20,tr) exten => 1000,1,Dial(SIP/phone1&SIP/phone2,20,tr) we are going to add a few more lines to the exten => 1000 entry to add voicemail:

exten => 1000,2,VoiceMail,u9999 exten => 1000,102,VoiceMail,b9999 add these lines after the entry for exten => 1000, it should look like this

exten => 1000,1,Dial(SIP/phone1&SIP/phone2,20,tr) exten => 1000,2,VoiceMail,u9999 exten => 1000,102,VoiceMail,b9999

What have we done? Well, the exten entries are like a list of things to do when we get a call. In this case we have said: exten => 1000,1,Dial(SIP/phone1&SIP/phone2,20,tr)

When extension 1000 rings (exten =>1000) , the first thing we do (exten =>1000,1) is dial phone1 and phone 2 (exten =>1000,1,Dial(SIP/phone1&SIP/phone2,20,tr)) and make it ring for 20 seconds. exten => 1000,2,VoiceMail,u9999 If the extension is not answered in the 20 seconds, the second entry will be executed, which is voicemail. The mailbox is specified by the u9999 at the end of the line. Now, this is all 'fine and dandy' but what if you are actually on the phone when the call comes in? Well, this is what the next line is for

exten => 1000,102,VoiceMail,b9999

There are 2 things to note here, the first is that the priority number has jumped way up to 102. This is a feature of Asterisk, and a useful one at that. When the call comes in and Asterisk tries to dial the extension 1000, if you are on the phone, Asterisk will jump to the current priority + 101 (n + 101). This gives us a priority of 102. The second thing to note is that the mailbox number at the end of the line is preceded by a b (b9999) this indicates that the busy message should be played to the user, and then the user should be allowed to leave a message. This is all very well, people can leave you messages, but at the moment you can't listed to them! Not really useful is it. We need to set up an extension so that you can actually get to the messages. there are 2 ways to set this up. The first is useful in home environments where you are only really going to have one mailbox or where you trust people completely: I say this because the first way to do it is to effectively not use the password.(I'll show you the other was in a moment). Under the exten => entries you've just added add the following lines. exten => 1001,1,Ringing exten => 1001,2,Wait(2) exten => 1001,3,VoicemailMain,s9999

I've 'padded' this out so that you can follow the chain of events when extension 1001 is dialed. Follow this sequence in this document (don;t actually try it on your phones yet) When extension 1001 is dialed the following things happen in the following order, 1. The phone gets a ringing tone 2. There is a 2 second wait (the phone is still getting the ringing tone) 3. The call is answered and goes straight to the voicemail menu for mailbox 9999 Note the user doesn't get asked for a password. The second way to do this is to omit the ',s9999' from the line giving:

exten => 1001,3,VoicemailMain When extension 1001 is dialed this time the following things happen in the following order,

1. The phone gets a ringing tone 2. There is a 2 second wait (the phone is still getting the ringing tone) 3. The call is answered and asked the user to enter a mailbox number, then a password. In our examples above you would enter 9999 as the mailbox and 1234 as the password (remember, we added the entry in voicemail.conf) Save your extensions.conf file ... Sorry but we've been doing quite a bit here and I want to make sure you remember to save the file. None of the changes you have made are functional yet, if you went to one of your phones and tried to dial extension 1001, you'd more than likely get a message telling you that the number was unavailable. We need to tell Asterisk to reload our .conf files.. So as before (and yes, I used cut and paste :P ): When you start asterisk without any parameters it runs as a daemon. Enter the following command: # asterisk If you get the error ERROR[8192]: File asterisk.c, Line 1249 (main): Asterisk already running on /var/run/asterisk.ctl. Use 'asterisk -r' to connect. then asterisk is already running and you should use the command # asterisk -r to connect to the daemon, adding vvvvvvvvvgc to this will give us debug information too ie: # asterisk -vvvvvvvgrc If the daemon was running and you got the error type reload

and hit enter at the prompt. If you did not get the error you do not need to do anything, however you might want to attach to the daemon anyway using. # asterisk -vvvvvvvgrc Now go to phone 1 and dial extension 1000, let phone 2 ring, don't answer it... You should hear a voice announce that "The person at extension 1000 is not available..." After the beep, leave yourself a message and then hang-up. Then dial extension 1001 and listen to your own message, make sure it all works.. Remember, when we first started, we set up a registration with FWD and allocated extension 1000 to it? Well, you've now added voicemail to your FWD number! If you are using Snom phones and the voicemail sounds 'funny', like the person is underwater add the following lines to your sip.conf under the general section disallow=all allow=ulaw allow=alaw Save the file, go to the Asterisk console and type reload and try calling the voicemail again...it should sound a lot better. Sadly this uses more bandwidth, but Snom has assured me that there will be a fix for this in their next firmware release.. (I have no date on when that will be) You're probably getting quite caught up in Asterisk by now, so take a look at the documentation, see if the sections we've covered make more sense to you now...Well, that's all for now, next time we'll look at Call parking, and meetme extensions.

Parking Zone.... Call parking is a wonderful invention, the best way to explain how useful it can be is to use a real world example. Imagine the scene, you're on your own in the office. Your desk is on the 2nd floor and the computer room is on the 4th. You are working late to fix a problem on one of the servers, but you need some help. You call another support team - they say they are busy but will call you back in 5 minutes. When they call you back they ask you to fiddle with the server. So, now you have a number of options 1. Say "hang on", run up stairs and do what they ask then run back and say "done that" only to hear them ask you to do something else. 2. Say "hang on, I'll transfer the call upstairs", you transfer the call to the computer room, run up stairs, pick up the phone in the computer room, run downstairs hang up, run upstairs and talk to the support team. 3. Say "hang on, I'll transfer the call upstairs", you park the call, hang up, run upstairs to the computer room and pick up the parked call. Now, it's clear that option 3 is the best for us. Parking the call, basically involves transferring the call to a 'fictional' extension that will hold the call until we either pick it up, the caller hangs up, or the timeout period expires. Call parking is a wonderful thing... embrace it with open arms So How do we do this with Asterisk? Well, it's simple. In your Asterisk config directory is a file called parking.conf. Let's take a look at it: # cd /etc/asterisk

Edit the file # vi parking.conf

You should see something similar to below. Let's take a closer look at it:

[general] parkext => 701 parkpos => 702-720 context => parkedcalls parkingtime => 1355 seconds)

; What ext. to dial to park ; What extensions to park calls on ; Which context parked calls are in ; Number of seconds a call can be parked for (default is 45

It should be self explanatory, but we'll go through it just to be sure you understand. parkext => is the extension you will dial to park a call. You will probably note that your parking.conf file has this number set at 700. I've changed mine to 701 because I was having an issue with Asterisk - although it would 'see' (looking at the console) I had tried to transfer to 700 it appeared not to believe that I had dialed it. This was essentially due to the 00 in the 700, changing it to 701 eliminates the problem completely. parkpos=> is the range of numbers used to park calls in the extract above I get 19 parking extensions, enough for me but you might like to expand it if you have more users. context=> is the context that you need to include to allow types of call to use call parking, this prevents external users parking YOU on your own system! parkingtime => is the length of time in seconds to park the call. Once this time expires the original extension will be called again. So how do you actually park a call? Well first of all, if we look back at the extensions we first created:

exten => 1,1,Dial(SIP/phone1,20,tr) exten => 2,1,Dial(SIP/phone2,20,tr)


you'll notice a couple of things that I haven't yet talked about. After the '20' (the number of rings) we have a 't' and an 'r'. The 't' means that the called user can transfer the call, the 'r' just means tell the calling party that the extension is ringing, but only send audio when the call is answered. We can actually modify these 2 lines, changing the 'tr' to 'Ttr' exten => 2,1,Dial(SIP/phone2,20,Ttr)

The 'T' allows the calling user to transfer the call as well. Be careful. you don't want an external user to be able to transfer your call around the system. Note: This is only 'SAFE' here because the 2 extensions we set up are not accessible from the outside world. In our current setup, all calls are sent to extension 1000 - just because it's physically the same device doesn't mean anything. So, do NOT add a 'T' to your 1000 extension line unless you REALLY REALLY want someone from the outside to transfer you on your system. I can't stress this enough, you don't want external callers messing with your setup. Edit your extensions.conf file and include the parking context in your [sip] section, so add include => parkedcalls just under the include => fwd line, it should look something like this... [sip] include => fwd include => parkedcalls Make these changes, save the file and go to the Asterisk console and type: reload Now dial from extension 'phone1' to extension 'phone2'. Pick up both ends of the call. Now on phone1 press the # key. You should hear a voice saying 'Transfer'. Dial the number you have in your parking.conf file that parkext =>points to. In my configuration that would be 701. If you don't dial the extension quickly enough the voice will say that it didn't recognize the extension number. If you dialed the extension number quickly enough then the voice will come back and give you an extension number, in the range specified in parkpos=> . Go back to phone2, if everything is working you should be hearing some music*, or a voice talking. Since we've only set up 2 phones, go back to phone1 and dial the extension that you were given when you parked the call. Once you dial that extension you should be connected back to phone 2. If you dial the wrong extension, the voice will tell you there is no parked call at that extension an hang up. In all honesty unless you have multiple parked calls, it's more than likely going to be the first extension specified in your parkpos=> range.

* the developers haven't added any music to the system, so unless you have done so yourself you'll get the default music on hold file, a mildly comical sentence. Meetme behind the bike sheds... Meetme is even easier to set up, there's very little to do here. There are however some potential pitfalls, everything tells us that a Zaptel card is required to use the Meetme functions, I have such a card so I cannot confirm that the use of ztdummy will be enough (remember we modified the Makefile at the top of this document to use ztdummy - effectively faking the presence of a Zaptel card) - I would however be interested in results from people who have tried only using ztdummy.. The Meetme function of Asterisk is like a conference call, multiple users can call in and either listed to a conference (one way) or actively take part (two way). One was conferencing can be useful if you don't want other participants to be heard, perhaps when someone is giving a presentation. We'll just set up a simple conference, a bit like a coffee room where everyone can talk and listen too. You should have got the hang of where the config files are, and how to get there and edit a file: # cd /etc/asterisk

Edit the file # vi meetme.conf

The file actually explains all you need to know, again we'll go through it to double check your understanding [rooms] ; ; Usage is conf => confno ;

conf => 1234 Ok, it's simple really, for each conference room you want to set up add a line conf => <room number> where <room number> is a unique number add the following line to the file: conf => 54321 Save the file, now edit your extensions.conf file again, # vi extensions.conf At the bottom of your [sip] section add a new extension: exten => 5557,1,Meetme,54321 The format of the Meetme line is: exten => <extension to dial>, Meetme,<room to enter> So when <extension to dial> is called, the Meetme application takes you to room <room to enter>. Save the file, and go to the Asterisk console and type

reload Now from phone1 dial, 5557. You should be told that you are the only one in the conference. Go to phone2 and also dial 5557. On phone1 you should hear a tone, signifying that someone has

entered the room, phone1 and phone 2 should now be in a conference. If you hang up phone1 phone 2 will hear an exit tone signifying that someone has left the conference. All these tones are fine for two or three people, but if you had 20 people coming and going it would get quite annoying. Thankfully we can turn this off. Edit your extensions.conf file again (you should still be in the /etc/asterisk directory ) # vi extensions.conf find the line you just added, exten => 5557,1,Meetme,54321

and change it adding |q - it should look like this: exten => 5557,1,Meetme,54321|q

Save the file, and go to the Asterisk console and type reload

Now call the conference number from both phones, note that the first phone gets no announcement that they are the only caller in the conference, and when the second phone enters no tone is played.

Configs! Configs? We dont need no stinkin configs


Well of course you know you do. Asterisk comes with a large number of configuration files, enough to daunt all but the most experienced. This next section will deal in detail with the main configurations that youll need to know about. The files covered in this section are: musiconhold.conf cdr_mysql.conf manager.conf adsi.conf meetme.conf oss.conf enum.conf mgcp.conf parking.conf voicemail.conf agents.conf extensions.conf modem.conf phone.conf vpb.conf alsa.conf festival.conf modules.conf privacy.conf iax.conf musiconhold.conf zapata.conf asterisk.conf indications.conf rpt.conf logger.conf sample.call Music on hold configurations Call record logging using mySQL Remote management configuration ADSI phone support Conference configurations o Call parking configurations Voicemail configurations Call agents Extension definitions Modem configurations phone config

CentOS 5 and Asterisk 1.4.x installation


Become an ITSP Now!

Become a serious competitor in VoIP Immediately FULL Consultancy, Installation, Training & Support Sell Hosted IP PBXs, Biz Lines, Call Centre Turnkey Provisioning at your data center

Base Install of Asterisk on a CentOS/RHEL box: Before you begin, you'll probably want to bring all your packages up to date. To do so, run 'yum -y update'. If any kernel files were updated as part of this process, you will need to reboot the machine (shutdown -r now). Repeat the process until no more updates are available. Download the pre-requisite of asterisk: gcc gcc-c++ kernel-devel bison openssl-devel libtermcap-devel

We'll be using yum for now(there's no support for apt-get in CentOS 5) yum -y update yum install gcc gcc-c++ kernel-devel bison openssl-devel libtermcap-devel then download the latest asterisk version at asterisk.org to /usr/src: cd /usr/src wget http://downloads.digium.com/pub/asterisk/asterisk-1.4-current.tar.gz wget http://downloads.digium.com/pub/zaptel/zaptel-1.4-current.tar.gz

#if you plan to use PRI cards(eg. TE110P, TE406P) you need to download this package: wget http://downloads.digium.com/pub/libpri/libpri-1.4-current.tar.gz then untar all the files tar -zxf zaptel-1.4-current.tar.gz tar -zxf asterisk-1.4-current.tar.gz tar -zxf libpri-1.4-current.tar.gz

### INSTALLING ZAPTEL ### cd /usr/src/zaptel make clean make make install #If you want "service zaptel restart" command to work do this make config

### INSTALL LIBPRI ### # If you are using E1 cards you need to install LIBPRI cd /usr/src/libpri make clean make make install

### INSTALLING ASTERISK ### cd /usr/src/asterisk ./configure make make install #If you want sample files to be created in /etc/asterisk make samples #If you want program docs/manual pages for asterisk make progdocs #If you want "service asterisk restart" command to work do this make config important notice: maybe some links are not available but you can refer to parent directory to find what your looking for or simply google your choice to download .

Asterisk and FreePBX on Ubuntu Server 10.10


The following packages will be installed:

Asterisk 1.6.2.7 FreePBX 2.8.1

I started with a fresh install of Ubuntu Server 10.10, but if you already have it installed, results should be similar. While installing I selected the LAMP and SSH services, those are pretty basic services which you will need. If you have finished a fresh install, or havent updated your system in a while, I suggest running the following lines before continuing with this guide. sudo apt-get update sudo apt-get upgrade

Postfix Although not necessary for running Asterisk and FreePBX, I suggest that you install a MTA agent. If you think this is unnecessary on your setup skip to the next section. Postfix is my MTA of choice, so we are going to install it. When prompt about which configuration should be done to it, select Internet with smarthost, just confirm the other options. sudo apt-get install postfix Okey, postfix installed, time to edit the basic configuration, add or change the following lines to /etc/postfix/main.cf: relayhost = [smtp.gmail.com]:587 smtp_sasl_auth_enable = yes smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd smtp_sasl_security_options = noanonymous smtp_tls_CAfile = /etc/postfix/cacert.pem smtp_use_tls = yes The password for accessing your external relay must be saved to /etc/postfix/sasl_passwd, add the following this file: [smtp.gmail.com]:587 user.name@gmail.com:password

Fix the permissions on this file: sudo chmod 400 /etc/postfix/sasl_passwd sudo postmap /etc/postfix/sasl_passwd Add the appropriate ca-certificate to /etc/postfix/cacert.pem. For gmail, thats Thawte Consulting, so add their ca-certificate. cat /etc/ssl/certs/Thawte_Premium_Server_CA.pem | sudo tee -a /etc/postfix/cacert.pem Restart postfix: sudo /etc/init.d/postfix restart

Avoid sending mail as root Edit /etc/aliases, add the following: root: server@domain.tld Run the new alias command: newaliases Create a /etc/postfix/sender_canonical file mapping user -> email such as: root server@domain.tld

Run the following lines: sudo postmap hash:/etc/postfix/sender_canonical Add the following line to /etc/postfix/main.cf: sender_canonical_maps=hash:/etc/postfix/sender_canonical Restart postfix: sudo /etc/init.d/postfix restart

PHP When you selected the LAMP service on your Ubuntu install, you automatically got PHP5 installed. Now you just have to install some additional packages that didnt get installed. So run the following line to install them. sudo apt-get install php5-gd php-pear php-db sox curl phpMyAdmin One might find useful to have phpMyAdmin installed for managing the MySQL database used by FrePBX and Asterisk. If you dont know what phpMyAdmin is, you can skip to the next section. Asterisk Ubuntu 10.10 provides pre-compiled asterisk packages, using that is way more easier than backing your own asterisk. Run the following to install it, and all of its dependencies. sudo apt-get install asterisk asterisk-mysql asterisk-mp3 asterisk-sounds-extra Dahdi This is a really short how-to for configuring Dahdi, it just covers the bare minimum, but it works ok. First of all, load the necessary kernel modules, in my case for a TDM400P it was the following line: sudo modprobe wctdm You might wanna check if the module was loaded and configured your hardware properly, so run a dmesg. If everything is alright, you have to create the dadhi configuration file. Thats really easy, just run: sudo dahdi_genconf -vvvv Warning: Be careful when you run this on a production system, it will override the current dahdi configuration file. Edit /etc/dahdi/system.conf and set the correct loadzone and defaultzone for your country code. I like to use vim to edit configuration files, but you can use any text editor. sudo vim /etc/dahdi/system.conf Now check if channels are up an running, run dahdi_cfg: sudo dahdi_cfg -vvv

Next you have to edit /etc/asterisk/chan_dahdi.conf to configure the channels, this is what asterisk will see and use to send and receive calls. Apache Before running the install command, you have to configure your apache server. I prefer to use virtual host, and as of lately I have adopted the following layout for my server:

/var/www/address/conf /var/www/address/public /var/www/address/log

In the conf I store the necessary vhost configuration, in public lives the public accessible files, and log hosts the logging files. Feel free to use your own personal taste on installing webapps. For those who want to stick with the how-to, create the needed directories: sudo mkdir /var/www/pabx.domain/ sudo mkdir /var/www/pabx.domain/conf sudo mkdir /var/www/pabx.domain/log sudo mkdir /var/www/pabx.domain/public Now create a /var/www/pabx.domain/conf/vhost.conf file: sudo vim /var/www/pabx.domain/conf/vhost.conf And paste the following lines, change it accordingly to your domain: 01.<VirtualHost *:80> 02. ServerName pabx.domain 03. ServerAlias pabx.domain 04. 05. ServerAdmin admin@domain.tld 06. ErrorLog /var/www/pabx.domain/log/error.log 07. CustomLog /var/www/pabx.domain/log/access.log combined 08. 09. DocumentRoot /var/www/pabx.domain/public 10. <Directory /var/www/pabx.domain/public>

11. 12. 13. 14.

Options Indexes FollowSymLinks MultiViews Order allow,deny AllowOverride All Allow from all

15. </Directory> 16. 17. <Directory /var/www/pabx.domain/public/admin> 18. 19. 20. 21. AuthType Basic AuthName "Restricted Area" AuthUserFile freepbx-passwd Require user admin

22. </Directory> 23.</VirtualHost> With the file created, add the vhost to the sites-enabled directory, with: sudo ln -s /var/www/pabx.domain/conf/vhost.conf /etc/apache2/sites-available/pabx.domain cd /etc/apache2/sites-enabled/ sudo ln -s ../sites-available/pabx.domain For now, create an htpasswd file to protect the access to freepbx. sudo htpasswd -c /etc/apache2/freepbx-passwd admin And finally, restart apache. sudo /etc/init.d/apache2 restart

FreePBX
Your Asterisk install should be working by now, so its time to install a nice web user interface. Ubuntu doesnt provide a package for FreePBX, so grab the latest stable source code from FreePBX site: http://www.freepbx.org/ cd /tmp wget http://mirror.freepbx.org/freepbx-2.8.1.tar.gz cd /usr/src sudo tar xvzf /tmp/freepbx-2.8.1.tar.gz cd freepbx-2.8.1/ You can equally extract the tarball on your home directory. It doesnt make any difference. Now its time to create the database, the user used to access it, and populate the basic tables. This will create and import the basic tables to asterisk and asterisk cdr database, run this from the recently extracted directory. mysqladmin create asterisk -u root -p mysqladmin create asteriskcdrdb -u root -p mysql -u root -p asterisk < SQL/newinstall.sql mysql -u root -p asteriskcdrdb < SQL/cdr_mysql_table.sql With the tables in-place, it's time to create the user with privileges to access and edit those tables. Open a mysql prompt with: mysql -u root -p On the prompt run the following queries:
GRANT ALL PRIVILEGES ON asterisk.* TO asterisk@localhost IDENTIFIED BY 'badasspassword'; GRANT ALL PRIVILEGES ON asteriskcdrdb.* TO asterisk@localhost IDENTIFIED BY 'badasspassword'; flush privileges; quit;

Don't forget to change the password! Before running the install command, make a copy of /etc/asterisk/modules.conf. FreePBX rewrites the file and trashes Asterisk installation. If you restart Asterisk after installing FreePBX Asterisk dies with no message. sudo cp /etc/asterisk/modules.conf ~/asterisk-modules.conf Ok, we are ready to install freepbx to /var/www/pabx.domain/public: sudo ./install_amp

The install script will ask for some configuration data, eg. were to install freepbx (/var/www/pabx.domain/public), sql password, asterisk password, etc. Take note of the passwords you used, you might need them later. The output from the install script is somewhat like this: ... Enter your USERNAME to connect to the 'asterisk' database: [asteriskuser] asterisk Enter your PASSWORD to connect to the 'asterisk' database: [amp109] badasspassword Enter the hostname of the 'asterisk' database: [localhost] Enter a USERNAME to connect to the Asterisk Manager interface: [admin] Enter a PASSWORD to connect to the Asterisk Manager interface: [amp111] Enter the path to use for your AMP web root: [/var/www/html] /var/www/pabx.domain/public Enter the IP ADDRESS or hostname used to access the AMP web-admin: [xx.xx.xx.xx] pabx.domain Enter a PASSWORD to perform call transfers with the Flash Operator Panel: [passw0rd] password Use simple Extensions [extensions] admin or separate Devices and Users [deviceanduser]? [extensions] Enter directory in which to store AMP executable scripts: [/var/lib/asterisk/bin] ... Restore asterisk-modules.conf file, which you backed up before installing FreePBX: sudo cp ~/asterisk-modules.conf /etc/asterisk/modules.conf Apache runs as www-data, Asterisk as user asterisk, so we have to change some permission to make both programs work together. First, add www-data to asterisk group: sudo adduser www-data asterisk Fix the permissions from amportal, add these lines to the end of /etc/amportal.conf: AMPASTERISKUSER=www-data AMPASTERISKGROUP=asterisk AMPASTERISKWEBUSER=www-data AMPASTERISKWEBGROUP=asterisk

Everything in place, time to start amportal: sudo amportal start Open your web browser and go to http://pabx.domain/ and you will be greeted with FreePBX site. I strongly suggest you to upgrade and install the FreePBX modules you will need, so go to Modules Admin and click on Check for online updates.

Start asterisk with amportal Before we finish, lets make amportal script to manage asterisk and run it through the safe_asterisk script, for that, we have to remove asterisk from rc.d: sudo update-rc.d -f asterisk remove Now edit safe_asterisk, to make sure it runs on background, edit the variable BACKGROUND to zero: sudo sed -e s/BACKGROUND=0/BACKGROUND=1/ -i /usr/sbin/safe_asterisk We have to start amportal after booting, so call amportal start in /etc/rc.local. Edit your /etc/rc.local and add the following line before the exit 0 line. /usr/local/sbin/amportal start Reboot your machine, and check that everything is still working

Asterisk installation on Fedora Core 2 final


This how-to guide outlines the process for a fresh installation of Redhat Linux (Fedora Core 2 Final) and Asterisk. The purpose of this document is to get you up and running (making and receiving phone calls) in about an hour. Experimenting with Asterisk, enabling more features and unlocking its potential is left up to you! This configuration was created and tested on: DELL PowerEdge 400SC ($350)

Intel Pentium 4 2.40Ghz 256MB RAM Standard configuration, no extra hardware

Installing Redhat Fedora Core 2 Final - Download Redhat Fedora Core 2 FINAL from http://fedora.redhat.com/download and burn the CD ISO images (you only need CDs 1 and 2) - Insert the CD and reboot into setup - Hit enter to start graphical setup - Skip the media test - After the graphical setup starts, click Next to continue - Select a language and click Next - Select a keyboard configuratoin and click Next - If asked, select "Install Fedora Core" and click Next - Select an installation type of Custom and click Next - Select Automatically Partition and click Next - If asked, select "Remove all partitions on this system". WARNING: This will erase ALL data on your computer! - Select Yes to confirm removing all data on your computer. - Click Next to accept default Disk Setup - Click Next to accept default Boot Loader Configuration - Click Next to accept default Network Configuration - Select No Firewall for the Firewall Configuration and click Next. WARNING: We do not recommend connecting this test server directly to the Internet! This server is configured without a firewall for simplicity. You can enable the firewall later and make the necessary changes to keep Asterisk working. - Click Next to accept default Additional Language Support

- Select a time zone and click Next - Enter a root password and click Next - For Package Group Selection, select ONLY the following and de-select the other options:

X Window System GNOME Desktop Editors Graphical Internet Text-based Internet Development Tools

- Click Next to accept Package Group Selection - Click Next to begin installation - Click Continue - Insert Disc 2 when prompted and click OK - When CD installation is complete, click Reboot - After rebooting, the post-installation process will begin - Click Next to continue - Accept the License Agreement and click Next - Set the date and time and click Next - Click Next to accept the default Display settings - Create a User Account with a different username and password than the "root" user created earlier and click Next - If asked, confirm your sound card and click Next - Click Next to skip the Additional CDs section - Click Next to Finish setup

Installing Asterisk - Login to your server as the user you created during install - Right-click on the background and select Open Terminal - Type "su -" on the command line, then enter the "root" user password when prompted - Run the following commands to download Asterisk: cd /usr/src export CVSROOT=:pserver:anoncvs@cvs.digium.com:/usr/cvsroot cvs login <--- This command will prompt for a password, use anoncvs cvs checkout asterisk - This will download the latest version of Asterisk to your server. WARNING: This will

download the very latest DEVELOPMENT version of Asterisk. It is NOT suitable for production use, just for testing! - Run the following commands to compile Asterisk: cd /usr/src/asterisk make clean make make install make samples

Note: You may need to "make install" several times before it really works.

Configuring Asterisk - Login to your server as user "root" - Right-click on the background and select Open Terminal

- Run the following commands to backup your current/sample configurations: cd /etc/asterisk mv iax.conf iax.backup mv extensions.conf extensions.backup - Run the following commands to download VoicePulse sample configurations: cd /etc/asterisk wget http://connect.voicepulse.com/samples/iax.sample wget http://connect.voicepulse.com/samples/extensions.sample - Run the following commands to rename the sample configurations: cd /etc/asterisk mv iax.sample iax.conf mv extensions.sample extensions.conf - Run the following commands to read and edit the VoicePulse Asterisk configurations:

cd /etc/asterisk gedit iax.conf & gedit extensions.conf & - In iax.conf, make the changes outlined in the QUICKSTART section of the sample file, save the file and close it. - In extensions.conf make the changes outlined in the QUICKSTART section of the sample file, save the file and close it.

Test incoming & outgoing calls

- Start Asterisk on your test server by running: /usr/sbin/asterisk -vvvgc - Run the following command to get the IP address of your Asterisk server: ifconfig - Look for the value after "inet addr:" to determine the IP address - Download "Dante's DIAX Software Phone" to your Windows PC: http://www.laser.com/dante/diax/diax.html - Start DIAX - Click on Config > Registration - Enter the following information (this "user" is already created in the sample iax.conf you downloaded from VoicePulse): Alias: VoicePulse Server: the IP address of your server that you determined above: http://www.voipinfo.org/wiki/view/the%20IP%20address%20of%20your%20server%20that%20you%20determi ned%20above Username: diax Password: diaxpassword Password: diaxpassword Register: checked: http://www.voip-info.org/wiki/view/checked - Click Save - Click OK - Dial a non-VoicePulse phone number to test outgoing calls like 1-888-225-5322 - You should see something similar to the following scroll across your Asterisk terminal

window: Accepting AUTHENTICATED call from 192.168.1.100, requested format = 2, actual format =2 Executing Dial("IAX2/diax@diax/3", "IAX2/MY_DEVICE_LOGIN:MY_DEVICE_PASSWORD@gwiaxt01.voicepulse.com/188822 55322") in new stack Call accepted by 66.234.228.160 (format GSM) - Add a phone number to your VoicePulse Connect! account from the Phone Numbers menu in your Account Center. - Dial the incoming VoicePulse Connect! phone number on your account from a non-VoicePulse phone. - You should see something similar to the following scroll across your Asterisk terminal window: Accepting AUTHENTICATED call from 66.234.228.170, requested format = 4, actual format =4 Executing Playback("IAX2/voicepulse-in-01@66.234.228.170:4569/4", "beep") in new stack - Dialing into your Asterisk server should read back your phone number to you and then read back any digits you dial. - If incoming and outgoing calls work, your Asterisk setup is complete! See www.asterisk.org or www.voip-info.org for more details on customizing your Asterisk setup.

Installing Asterisk Real-Time-way one


The basic asterisk system is sufficient for simple testing of the OpenBTS system. However, it does not support secure connections, as all communications go through the external context. Similarly, Asterisk is unable to dynamically route calls without the Subscriber Registry, If you need any of these features, you will need to install Asterisk Real-Time: http://www.voipinfo.org/wiki/view/Asterisk+RealTime which pulls all of it's needed information from a set of connected databases. This is detailed here.

Asterisk Realtime Configuration Below are directions for getting Realtime working with Sqlite3 in Asterisk. It would be really sweet if someone wrote a script to do all of this! Cleaning up prior install sqlite3 and asterisk are both pulled in via Apt with the "simple" install. Make sure to remove those two packages to allow you to build new ones from source. sudo apt-get remove asterisk sqlite3 sudo apt-get autoremove Installing required software in the operating system

Download sqlite3, available from the packages branch. o configure, make, make install o sqlite3 must be compiled with SQLITE_ENABLE_COLUMN_METADATA defined, so it's ./configure CFLAGS="DSQLITE_ENABLE_COLUMN_METADATA -O2" sudo apt-get install libsqlite3-dev If you are going to install Erlang anyway, do that now with apt-get install since it includes ODBC. Otherwise: o download unixODBC from http://www.unixodbc.org This is available from the packages branch in SVN. o configure, make, make install download sqliteodbc: http://www.ch-werner.de/sqliteodbc/ . This is available from the packages branch in SVN. configure, make, make install

(Re)Building Asterisk Note that if asterisk was already built, then after downloading the software above you need to redo

./configure --disable-xmldoc make menuselect o Make sure Sqlite3 and ODBC are selected, especially in "applications", "resource modules" and "dialplan functions". o Make sure "res_realtime" is selected in "resource modules". o You should NOT see "XXX" on the Sqlite3 and ODBC selections anywhere in the configuration menus. If you see "XXX" for Sqlite3 or ODBC features anywhere, that means that those packages are not installed correctly (or at least in the way that Asterisk expects to see them). Look at the config.log file for clues. If you are building a full BTS unit, you will need to install Erlang with apt-get install and that will include an ODBC installation that Asterisk likes. make make install

Yes, you need to rebuild Asterisk. And if you are going to add Speex support, this would be the time to do it. You are supposed to be able to install Speex with apt-get install, but I have not gotten that to work yet.

ODBC configuration files

/etc/odbcinst.ini
[SQLite3] Description=SQLite3 ODBC Driver Driver=/usr/local/lib/libsqlite3odbc.so Setup=/usr/local/lib/libsqlite3odbc.so Threading=2

/etc/odbc.ini
[asterisk] Description=SQLite3 database Driver=SQLite3 Database=/var/lib/asterisk/sqlite3dir/sqlite3.db # optional lock timeout in milliseconds Timeout=2000

You will also need symbolic links to the files in the following places:

/usr/local/etc/odbcinst.ini /usr/local/etc/odbc.ini /root/.odbcinst.ini /root/.odbc.ini ~openbts/.odbcinst.ini ~openbts/.odbc.ini

In other words, as root: cd /usr/local/etc; ln -s /etc/odbc.ini; ln -s /etc/odbcinst.ini cd /root; ln -s /etc/odbc.ini .odbc.ini; ln -s /etc/odbcinst.ini .odbcinst.ini cd ~openbts; ln -s /etc/odbc.ini .odbc.ini; ln -s /etc/odbcinst.ini .odbcinst.ini You might also need symbolic links in the asterisk home directory if asterisk is running as user asterisk: cd ~asterisk; ln -s /etc/odbc.ini .odbc.ini; ln -s /etc/odbcinst.ini .odbcinst.ini The standard for configured BTS units is actually to put the real files in /usr/local/etc and then put symbolic links in:

/etc ~root

If Asterisk is running, modifying these files might make it crash. Be aware of that.

Asterisk configuration files

modules.conf

Autoload must be enabled, plus make sure you're not overriding that by telling it NOT to load particular files, like res_config_odbc.so. The noload is commented out here. [modules] autoload=yes ; noload => res_config_odbc.so

extconfig.conf

This tells asterisk to use odbc for realtime sip. There was some confusion about whether the second field (asterisk, here) is the database, the odbc database handle, or the odbc context. I made them all the same to avoid figuring it out. [settings] sipusers => odbc,asterisk,sip_buddies sippeers => odbc,asterisk,sip_buddies

res_odbc.conf

Standard odbc configuration. Everything named "asterisk" to avoid confusion. [asterisk] enabled => yes dsn => asterisk pre-connect => yes

func_odbc.conf

This let's you use the function ODBC_SQL to execute any SQL statement in the dialplan. We use that to get the SIP number given the extension. [SQL] dsn=asterisk

readsql=${ARG1}

extensions.conf

Here's how the dialplan uses the ODBC_SQL function to get the SIP number from the extension. This is just here as an example, though. Use the extensions.conf file in openbts/trunk/AsteriskConfigs.
[phones] ; This is the context for handsets provisioned through the realtime database. exten => _N.,1,Set(Name=${ODBC_SQL(select dial from dialdata_table where exten = \"${EXTEN}\")}) exten => _N.,n,GotoIf($["${Name}" = ""] ?outbound-trunk,${EXTEN},1) exten => _N.,n,Set(IPAddr=${ODBC_SQL(select ipaddr from sip_buddies where name = \"${Name}\")}) exten => _N.,n,GotoIf($["${IPAddr}" = ""] ?outbound-trunk,${EXTEN},1) exten => _N.,n,Dial(SIP/${Name}@${IPAddr}:5062)

In this example, OpenBTS has it's inbound SIP interface at port 5062 and the context "outboundtrunk" is used for handling phones not provisioned in the realtime database. Sqlite3 database location The default path for the Asterisk realtime database file is /var/lib/asterisk/sqlite3dir/sqlite3.db. (Note that this path was referenced above in /etc/odbc.ini.) The sqlite3 database file must be readable and writable by asterisk, smqueue and sipauthserve, AND the directory in which the sqlite3 database file is located must ALSO be readable and writable by the applications. This is because sqlite3 generates temporary files in the directory.

Asterisk RealTime-way 2
The Asterisk RealTime Architecture

ARA, the Asterisk Realtime Architecture is one of the major new features in Asterisk version 1.2.

Background Information From docs/README.extconfig The Asterisk external configuration engine is the result of work by Anthony Minessale II, Mark Spencer and Constantine Filin It is designed to provide a flexible, seamless integration between Asterisk's internal configuration structure and external SQL other databases (maybe even LDAP one day). External configuration is configured in /etc/asterisk/extconfig.conf allowing you to map any configuration file (static mappings) to be pulled from the database, or to map special runtime entries which permit the dynamic creation of objects, entities, peers, etc. without the necessity of a reload.

Olle explains the world In the new RealTime architecture, all database specific code is moved to database specific drivers. The channel just calls a generic routine to do database lookup. Much cleaner, simpler and manageable from a coding standpoint.

The database is accessed with three functions:


STATIC: This is used to load static configuration when a module is loaded REALTIME: This is used to lookup objects during a call (or another event) UPDATE: This is used to update objects

The database support in the channel is not changed. There are "normal" static peers/users and

database peers/users. The static ones, regardless if these are loaded from a text file or a database configuration, are kept in-memory and in the SIP channel we provide them with NAT traversal support and message waiting indication if needed.

The database peers/users are not kept in memory. These are only loaded when we have a call and then deleted, so there's no support for NAT keep-alives (qualify=) or voicemail indications for these peers.

NOTE: If you enable RealTime caching in your sip.conf, Voicemail MWI works and so does 'sip show peers' - see rtcachefriends=yes. The downside to this is that if you change anything in the database, you need to do a 'sip reload' (for major changes) or 'sip prune realtime PEERNAME' (for single peer changes) before they become active.

In laymans terms In the Stable 1.0.X branch of Asterisk, database storage of configuration files and parameters was done mostly by hardcoding connection and query code directly into the application. The best example of this is in app_voicemail, where you can see MySQL code and PostgreSQL code all meshed with the app_voicemail code.

This method of database retrevial proves to be ugly as all the asterisk code is now crammed with database specific code that is irrelevant to the function of the application at hand. Thus RealTime was developed as a means to remove the code and replace it with a unified (abstracted) database retrevial method.

Terminology/Files Driver - A compiled module containing database specific code that accepts the generalized function calls that RealTime makes. As of this writing, only ODBC, MySQL (via asterisk-addons) and LDAP (see http://free.oxymium.net/Asterisk/ and http://bugs.digium.com/view.php?id=5768) drivers are available. Family - A name associated with a RealTime call. Examples: sippeers, sipusers, voicemail. extconfig.conf - The configuration file that contains the information necessary to bind specific families to specific drivers. res_odbc.conf - The configuration file for ODBC RealTime. res_mysql.conf - The configuration file for MySQL RealTime. res_ldap.conf - The configuration file for LDAP RealTime.

ODBC - Open DataBase Connectivity: http://www.webopedia.com/TERM/O/ODBC.html MySQL - the world's most popular open source database: http://www.mysql.com/ OpenLDAP - Open source implementation of the Lightweight Directory Access Protocol http://www.openldap.org/

There are 2 methods of using RealTime: ODBC and MySQL. Yes, you can use ODBC to connect to MySQL and many other ODBC supported databases. (Being an avid MySQL user and advocate, I didn't want to bother with ODBC so I wrote the RealTime MySQL driver over the weekend.) How to configure RealTime - ODBC Method (This paragraph assumes you have ODBC already running and installed on your box.) When you start to compile Asterisk, the Makefile inside res/ should detect if you have ODBC properly installed and if so compile the res_config_odbc.so module for you (as long as you have the unixODBC-dev libraries installed : http://sourceforge.net/project/showfiles.php?group_id=1544&package_id=122072). Go into /etc/asterisk/res_odbc.conf and configure your ODBC connections. Some sample configs are supplied in asterisk/configs/res_odbc.conf.sample NOTE: res_config_odbc.conf is deprecated and will not be loaded. Skip to 'Extconfig'

How to configure RealTime - MySQL Method (it is assumed you have the MySQL client libraries/headers installed on your box.) Check out asterisk-addons from CVS: http://www.voipinfo.org/wiki/view/Asterisk+addon+asterisk-addons cd /usr/src/ svn co http://svn.digium.com/svn/asterisk-addons/trunk asterisk-addons

Go into asterisk-addons and run the following commands configure make

make install (This will also compile and install the other stuff in addons so if you don't want/need it, just run 'make' and manually copy res_config_mysql.so to your modules directory.) Copy asterisk-addons/configs/res_mysql.conf.sample to /etc/asterisk/res_mysql.conf Edit this file to your liking. At this time, the MySQL drivers supports multiple databases on only one server.

Now edit /etc/asterisk/extconfig.conf

Extconfig - Static Configs Static configuration is where you can store regular *.conf files into the database. These configurations are read at Asterisk startup/reload. Some modules may also re-read this info upon their own reload (Ex. sip reload).Here is the format for a static config: [settings] <conf filename> => <driver>,<databasename>~np~[~/np~,table_name~np~]~/np~ queues.conf => odbc,asterisk,ast_config sip.conf => mysql,asterisk iax.conf => ldap,MyBaseDN,iax Above we have 3 examples. The first example will bind 'queues.conf' to the table 'ast_config' located in the database context 'asterisk' using the ODBC driver. NOTE (LN): this is NOT the database you specified in /etc/odbc.ini, rather it's the context in /etc/asterisk/res_odbc.conf that you are using to connect to the ODBC driver! The second example will bind 'sip.conf' to the table 'sip.conf' (because we ommited the table name, it defaults to the file name) in the database 'asterisk' using the MySQL driver. The 3rd one will bind iax.conf to the 'table' iax.conf in the ldap database using LDAP driver; MyBaseDN is the base DN for the query. Using the above examples, now, when app_queue.so loads, the RealTime ODBC driver will execute a query and get the information it needs. The same is true for chan_sip.so, but with MySQL and chan_iax.so with LDAP. Extconfig - RealTime RealTime configuration is where configuration values are read/updated in real time. Example: Lets say you have 2 SIP users defined in your sip.conf and you want to add a 3rd. You

add them to the file then execute the command 'sip reload'. This re-reads your sip.conf and allows the 3rd to register. With RealTime, all you do is add 1 new record to the table that sipusers has been bound to. No reloading necessary. RealTime maps take the following fomat: [settings] <family name> => <driver>,<database name>~np~[~/np~,table_name~np~]~/np~ sippeers => mysql,asterisk,sip_peers sipusers => mysql,asterisk,sip_users queues => mysql,asterisk,queue_table queue_members => mysql,asterisk,queue_member_table meetme => mysql,asterisk,meetme_table voicemail => mysql,asterisk^ Above we have four examples. The first example will bind the family name "sippeers" to the table "sip_peers" in the database "asterisk" using the MySQL driver. The last example will bind the family name "voicemail" to the table "voicemail" (because we ommited the table name, it defaults to the family name) in the database "test" using the MySQL driver. It is worth noting that sipusers and sippeers may both refer to the same table, if you wish. NOTE: extconfig.conf is parsed each time you connect to the asterisk CLI.

Now that you have created all the necessary binds, it is time to create the tables. Since the tables are different to each family, I've broken the Wiki pages down to eliminate 1 huge RealTime page. Scroll down to the bottom to find the individual family pages. NOTE: If you are setting up only IAX users (no peers), both iaxusers and iaxpeers entries in the above file need to be either included (uncommented) for iax users/peers to be loaded from the database.

Conclusions RealTime is great. With a nice web interface you can allow customers limited ability to edit their own dialplan without needing a reload.

RealTime support is currently available for the following families:


sippeers sipusers iaxpeers iaxusers voicemail musiconhold queues and queue_members (used together for the Queue application). extensions NOTE: The family name for RealTime extensions can be whatever you want. Please read Asterisk RealTime Extensions for more info.

More information will be posted as more apps become RealTime enabled. Notes Q: Does anyone know how to send * a semi-colon from a realtime database. I know that * uses the semi-colon as a 'seperator' - but I need to be able to use one in a command. I know I can use \; in the non-realtime configs, but this doesn't work in realtime. A: in /etc/asterisk/extensions.conf globals SEMICOLON=\; Then use ${SEMICOLON} in realitime.... Hacky, but it's what I'm using at the moment.. If you use SVN (upcoming 1.4.37, 1.6.2.14, or 1.8.0), you can encode semicolons in the database as the literal string "^3B".

asterisk-addons
http://www.asterisk.org/index.php?menu=download asterisk-addons - An addons package, which includes MySQL support for call detail records and MP3 support for MOH

Installation You must have MySQL installed and the development package prior to installing the app_addon_sql_mysql module. You must already have Asterisk installed before following the directions below. You must also have the DBD::mysql perl module installed!! Ensure your root@localhost user does not have a password then run the following: perl -MCPAN -e "install DBD::mysql" You can then apply your root@localhost password again (or make sure that you have an empty password for root, but be aware...) You need to use svn or download a ready-made .tar file in order to retrieve the "asterisk-addons": 1. cd /usr/src (the following command retrieves an old version of the addons. much better to get the current version of digium's site: http://ftp.digium.com/pub/asterisk/ currently) 1. svn checkout http://svn.digium.com/svn/asterisk-addons/branches/1.2 asterisk-addons

Compile /usr/src/asterisk-addons as follows: 1. cd asterisk-addons 2. make clean 3. make install

Asterisk RealTime Extensions


extconfig.conf Setup
Add the following line, swapping your own personal values if you wish:

extensions => mysql,asterisk,extensions_table You can change mysql to odbc if you want to use odbc. You can change asterisk to be the name of your database. You can change extensions_table to be the name of the extensions table we will create below. modules.conf Setup Don't forget to load the proper modules or Strange Things (TM) will happen. autoload=yes or explicitly list them out: load => res_config_mysql.so load => app_realtime.so load => func_realtime.so load => pbx_realtime.so (props to Corydon76 for setting a few of us straight) extensions.conf Setup The way RealTime Extensions work is through a switch statement in the dialplan. Here is an example of my context:

[test] ; ; switch => Realtime/[context]@[family][/options] ; If context is not given, current context is default ; If family is not given, family of 'extensions' is default ; switch => Realtime/mycontext@realtime_ext This tells Asterisk that any call into the 'test' context are to be switched to RealTime using the context "mycontext" and the family name "realtime_ext".

context is optional: (switch => Realtime/@realtime_ext) and if left off, RealTime will use the current context, in this case "test". family is also optional: (switch => Realtime/@) and if left off, RealTime will use the family name "extensions". Currently there are no supported options so you can leave it off. The family name above can be anything you wish. Just be sure it matches the family name you have stored in extconfig.conf: ( realtime_ext => mysql,asterisk,extensions_table ) And YES! You can have multiple switches and multiple family names using this method. NOTE: It seems like Asterisk 1.6.0 always matches the realtime context with the name of the static context that contains the switch statement. The above example will always seek for the "Test" context in the database and not for the "mycontext". So you might as well use: [test] switch => Realtime

Database Table Now lets create the table we need: NOTE: You can use any table name you wish, just make sure the table name matches what you have the above family name bound to. NOTE: You should REALLY add indices for the context, exten and priority columns, as your asterisk system might slow down considerably otherwise.

# # Table structure for table `extensions_table` # CREATE TABLE `extensions_table` ( `id` int(11) NOT NULL auto_increment, `context` varchar(20) NOT NULL default '', `exten` varchar(20) NOT NULL default '', `priority` tinyint(4) NOT NULL default '0',

`app` varchar(20) NOT NULL default '', `appdata` varchar(128) NOT NULL default '', PRIMARY KEY (`context`,`exten`,`priority`), KEY `id` (`id`) ) TYPE=MyISAM; # # Dumping data for table `extensions_table` # INSERT INTO `extensions_table` VALUES (1, 'mycontext', '_574555XXXX', 1, 'Wait', '2'); INSERT INTO `extensions_table` VALUES (2, 'mycontext', '_574555XXXX', 2, 'SayNumber', '102'); INSERT INTO `extensions_table` VALUES (3, 'mycontext', '2815551212', 1 , 'Playback', 'pbxinvalid');

Matthen Boehm writes: Here are some "complicated" extensions that work in my RealTime extensions: INSERT INTO `extensions` (`id`, `context`, `exten`, `priority`, `app`, `appdata`) VALUES (5, 'cytel', '8322008630', '1', 'Dial', 'SIP/3044,30'); INSERT INTO `extensions` (`id`, `context`, `exten`, `priority`, `app`, `appdata`) VALUES (7, 'cytel', '80', '1', 'Voicemailmain', '@cytel'); INSERT INTO `extensions` (`id`, `context`, `exten`, `priority`, `app`, `appdata`) VALUES (8, 'cytel', '_832.', '1', 'Dial', 'SIP/${EXTEN}@66.88.74.85|30'); INSERT INTO `extensions` (`id`, `context`, `exten`, `priority`, `app`, `appdata`) VALUES (9, 'cytel', '_9X.', '1', 'Dial', 'IAX2/devasterisk:asterisk@asterisk-alpha/${EXTEN}@cytel-internal'); INSERT INTO `extensions` (`id`, `context`, `exten`, `priority`, `app`, `appdata`) VALUES (10, 'cytel', '3013', '1', 'Dial', 'SIP/3013|30'); INSERT INTO `extensions` (`id`, `context`, `exten`, `priority`, `app`, `appdata`)

VALUES (11, 'cytel', '_3XXX', '1', 'Dial', 'IAX2/devasterisk:asterisk@asterisk-alpha/${EXTEN}@cytel-internal');

RZero Writes : If you want to import your current extension.conf to be used in realtime with this set up use this php script http://pastebin.com/SqNRJdbD It parses the extension.conf and inserts the data in the correct order with the priority set correctly when using `n` as well as contexts also it will run a check to ensure that you don't have any duplicated entries before inserting the data if you are importing from more than one server. Don't forget to make your script executable ! Ps sorry to having to use the pastebin its because of the the script looks messed up when pasted into here.

When calling a macro from the extensions_conf database you need to pipe delimit your appdata where asterisk doesn't convert the commas to pipes when it parses the data. So an example of an extensions_conf insert statement for a Macro entry would look like: Insert into extensions_conf (context,exten,priority,app,appdata) values ('internal','1234','1','Macro','ExtensionDial|1234|SIP/1234@gateway'); In the database it would look like the following: context exten priority app appdata internal 1234 1 Macro ExtensionDial|1234|SIP/1234@gateway

Caveats Although Asterisk can handle pattern extension names in a realtime DB, there is something you ought to know. They can severely slow down Asterisk.

Why? Because Asterisk will first attempt to do a direct match db lookup first for any lookup by extension. If it succeeds, all is well. But if it does not succeed, then it will sequentially load every extension in the context, and sequentially test to see which best matches the input number. If you have a small number of extensions, this is usually not a big deal. But if you have hundreds or thousands of extensions, finding the best match could take several seconds! So, as a rule of thumb, do not put extension patterns in your realtime database. In 1.6, there is code added to the core pbx to use a trie-based search that makes the pattern search time almost constant, no matter how many patterns. But this is not possible in a realtime database situation. It must continue to use the old technique which involves testing all patterns in a context to find the 'best' match, which grows exponentially slower with the number of patterns. If you absolutely must use patterns, keep them in the in-memory dialplan (extensions.ael, extensions.conf). Let the DB do the exact matches in large datasets that it is built for. There is a patch which adds an option to the Realtime switch which disables the search for extension pattern in the database: http://bugs.digium.com/view.php?id=13698 One more thing: It is usually wise to separate program from data. Keep the logical control dialplan stuff in extensions.ael and extensions.conf, and reserve realtime lookups for true database lookups. Keep extensions.conf and extensions.ael in some sort of source-control system, like cvs, subversion, or git, so you can track your changes and have some backup. Just because you CAN store your dialplan in a database, doesn't mean it would be practical, expedient, or right to do so.

Testing Now place a call into the [test] context. Asterisk should query the associated database/table for the number you dialed. So if you dial 5745558896, you should Wait(2), then hear Allison saying the numbers "one zero two".

If you dial 2815551212 you would hear Allison saying "I'm sorry. That's not a valid extension" The 'i' and 's' extensions are currently not supported. The 't' extension is supported. Edit: Latest CVS will accept 'i' and 's' / rowitech

Note on using Goto and GotoIf in the extensions table (and DIAL!)

When using a Goto or GotoIf or Dial command you may only use '|' in the app_data field of the command and not ','. For example, the app_data field must take the form of context|s|1 and not context,s,1. Or if using dial, it should be SIP/user|60|Tt, not SIP/user,60,Tt.

UPDATE inserting extensions using id values in the examples doesn't make any real sense on an autoincrement primary key field INSERT INTO `extensions_table` VALUES (1, 'mycontext', '_574555XXXX', 1, 'Wait', '2'); would be better inserted as: INSERT INTO `extensions_table` VALUES (NULL, 'mycontext', '_574555XXXX', 1, 'Wait', '2'); etc Cheers

Asterisk RealTime Sip


Asterisk RealTime SIP sip.conf Setup You can keep any sip users in the flatfile AND use RealTime. How cool is that? Extconfig.conf Setup with Asterisk 1.6.1.1 Add the following line, swapping your own personal values if you wish:
sipusers => mysql,general,sip_buddies sippeers => mysql,general,sip_buddies extensions => mysql,general,extensions_table

Database Config put the following in res_mysql.conf [general] dbhost = 127.0.0.1 dbname = asterisk dbuser = myuser dbpass = mypass dbport = 3306 note: Values in sip.conf or iax.conf like in older versions of * are no longer used.

Database Table Lets create the table we need: NOTE: You can use any table name you wish, just make sure the table name matches what you have the family name bound to. NOTE: General principles: the column names in your database table correspond to the option names in sip.conf. You do not have to have all option names defined in your table; you only have to define those columns you actually use in sip.conf. Exceptions to this are 'regserver' and 'regseconds', which the channel driver's realtime routines use for internal book-keeping. The 'name' field must also be present to hold equivalent of the category name in the sip.conf file. It is easily possible that different versions of Asterisk will require different tables. For instance, a 1.6

version of Asterisk would not use the "cancallforward", or 'restrictcid', or 'mask', or 'qualify', or "musiconhold" columns, but might require 'mohinterpret', 'mohsuggest', etc. etc. options instead. Options (column names) that not offered in sip.conf are ignored. Some options in sip.conf are OK to have multiple entries, but in a real-time database, Only one column is available. In these cases, you can add multiple values separated by semicolons. This occurs with setvar, allow/disallow, and permit/deny. NOTE: Column order is important!! If you place "ipaddr" before "host" (in the case of dynamic), you will never load the public IP address of your sip device, as it will be overwritten when "host" is encountered. allow/disallow and permit/deny, the order of these statements is crucial in the config file, as they are applied in order. In the realtime db, the order is determined by the order of the columns in the table. You will note that the deny/disallow entries come before the allow/permit entries, to support the common usage of 'deny all', then permit '192.168.....'.

# # Table structure for table `sip_buddies` # CREATE TABLE `sip_buddies` ( `id` int(11) NOT NULL auto_increment, `name` varchar(80) NOT NULL default '', `host` varchar(31) NOT NULL default '', `nat` varchar(5) NOT NULL default 'no', `type` enum('user','peer','friend') NOT NULL default 'friend', `accountcode` varchar(20) default NULL, `amaflags` varchar(13) default NULL, `call-limit` smallint(5) unsigned default NULL, `callgroup` varchar(10) default NULL, `callerid` varchar(80) default NULL, `cancallforward` char(3) default 'yes', `canreinvite` char(3) default 'yes', `context` varchar(80) default NULL, `defaultip` varchar(15) default NULL, `dtmfmode` varchar(7) default NULL, `fromuser` varchar(80) default NULL, `fromdomain` varchar(80) default NULL, `insecure` varchar(4) default NULL, `language` char(2) default NULL,

`mailbox` varchar(50) default NULL, `md5secret` varchar(80) default NULL, `deny` varchar(95) default NULL, `permit` varchar(95) default NULL, `mask` varchar(95) default NULL, `musiconhold` varchar(100) default NULL, `pickupgroup` varchar(10) default NULL, `qualify` char(3) default NULL, `regexten` varchar(80) default NULL, `restrictcid` char(3) default NULL, `rtptimeout` char(3) default NULL, `rtpholdtimeout` char(3) default NULL, `secret` varchar(80) default NULL, `setvar` varchar(100) default NULL, `disallow` varchar(100) default 'all', `allow` varchar(100) default 'g729;ilbc;gsm;ulaw;alaw', `fullcontact` varchar(80) NOT NULL default '', `ipaddr` varchar(15) NOT NULL default '', `port` smallint(5) unsigned NOT NULL default '0', `regserver` varchar(100) default NULL, `regseconds` int(11) NOT NULL default '0', `lastms` int(11) NOT NULL default '0', `username` varchar(80) NOT NULL default '', `defaultuser` varchar(80) NOT NULL default '', `subscribecontext` varchar(80) default NULL, `useragent` varchar(20) default NULL, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`), KEY `name_2` (`name`) ) ENGINE=MyISAM ROW_FORMAT=DYNAMIC; July/15,2010 Sherwood McGowan - Sherwood McGowan Consulting Here's a table definition that should not only cover all 1.6.x config items, but it should also be a little "cleaner" since it uses enums for options that have only couple or so possible values. Nov/4,2010 Nick Barnes - Vitell Updated to work with latest 1.6.x and moved 'deny' above 'permit' otherwise nothing will work! Sherwood: Thanks Nick for catching that!

# Asterisk 1.6.x structure for sip 'device' table CREATE TABLE `sip_devices` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(80) NOT NULL DEFAULT '', `context` varchar(80) DEFAULT NULL, `callingpres` enum('allowed_not_screened','allowed_passed_screen','allowed_failed_screen','allowed','prohib_ not_screened','prohib_passed_screen','prohib_failed_screen','prohib','unavailable') DEFAULT 'allowed_not_screened', `deny` varchar(95) DEFAULT NULL, `permit` varchar(95) DEFAULT NULL, `secret` varchar(80) DEFAULT NULL, `md5secret` varchar(80) DEFAULT NULL, `remotesecret` varchar(250) DEFAULT NULL, `transport` enum('tcp','udp','tcp,udp') DEFAULT NULL, `host` varchar(31) NOT NULL DEFAULT '', `nat` varchar(5) NOT NULL DEFAULT 'no', `type` enum('user','peer','friend') NOT NULL DEFAULT 'friend', `accountcode` varchar(20) DEFAULT NULL, `amaflags` varchar(13) DEFAULT NULL, `callgroup` varchar(10) DEFAULT NULL, `callerid` varchar(80) DEFAULT NULL, `defaultip` varchar(15) DEFAULT NULL, `dtmfmode` varchar(7) DEFAULT NULL, `fromuser` varchar(80) DEFAULT NULL, `fromdomain` varchar(80) DEFAULT NULL, `insecure` varchar(4) DEFAULT NULL, `language` char(2) DEFAULT NULL, `mailbox` varchar(50) DEFAULT NULL, `pickupgroup` varchar(10) DEFAULT NULL, `qualify` char(3) DEFAULT NULL, `regexten` varchar(80) DEFAULT NULL, `rtptimeout` char(3) DEFAULT NULL, `rtpholdtimeout` char(3) DEFAULT NULL, `setvar` varchar(100) DEFAULT NULL, `disallow` varchar(100) DEFAULT 'all', `allow` varchar(100) DEFAULT 'g729;ilbc;gsm;ulaw;alaw', `fullcontact` varchar(80) NOT NULL DEFAULT '', `ipaddr` varchar(15) NOT NULL DEFAULT '',

`port` mediumint(5) unsigned NOT NULL DEFAULT '0', `username` varchar(80) NOT NULL DEFAULT '', `defaultuser` varchar(80) NOT NULL DEFAULT '', `subscribecontext` varchar(80) DEFAULT NULL, `directmedia` enum('yes','no') DEFAULT NULL, `trustrpid` enum('yes','no') DEFAULT NULL, `sendrpid` enum('yes','no') DEFAULT NULL, `progressinband` enum('never','yes','no') DEFAULT NULL, `promiscredir` enum('yes','no') DEFAULT NULL, `useclientcode` enum('yes','no') DEFAULT NULL, `callcounter` enum('yes','no') DEFAULT NULL, `busylevel` int(10) unsigned DEFAULT NULL, `allowoverlap` enum('yes','no') DEFAULT 'yes', `allowsubscribe` enum('yes','no') DEFAULT 'yes', `allowtransfer` enum('yes','no') DEFAULT 'yes', `ignoresdpversion` enum('yes','no') DEFAULT 'no', `template` varchar(100) DEFAULT NULL, `videosupport` enum('yes','no','always') DEFAULT 'no', `maxcallbitrate` int(10) unsigned DEFAULT NULL, `rfc2833compensate` enum('yes','no') DEFAULT 'yes', `session-timers` enum('originate','accept','refuse') DEFAULT 'accept', `session-expires` int(5) unsigned DEFAULT '1800', `session-minse` int(5) unsigned DEFAULT '90', `session-refresher` enum('uac','uas') DEFAULT 'uas', `t38pt_usertpsource` enum('yes','no') DEFAULT NULL, `outboundproxy` varchar(250) DEFAULT NULL, `callbackextension` varchar(250) DEFAULT NULL, `registertrying` enum('yes','no') DEFAULT 'yes', `timert1` int(5) unsigned DEFAULT '500', `timerb` int(8) unsigned DEFAULT NULL, `qualifyfreq` int(5) unsigned DEFAULT '120', `contactpermit` varchar(250) DEFAULT NULL, `contactdeny` varchar(250) DEFAULT NULL, `lastms` int(11) NOT NULL, `regserver` varchar(100) NOT NULL DEFAULT '', `regseconds` int(11) NOT NULL DEFAULT '0', `useragent` varchar(50) NOT NULL DEFAULT '', PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`),

KEY `name_2` (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC Apr 27/10 Serge Berney - iXo SA Since 1.6.1.18 : Added 'useragent' To prevent the warning message : "Table sip_buddies requires a column 'useragent' of size '20', but no such column exists." If you have error message like : WARNING27599 acl.c: Invalid IP address in ERROR27599 chan_sip.c: Bad ACL entry in configuration line 0 : http://www.voip-info.org/wiki/view/27599 http://www.voip-info.org/wiki/view/27599 Be sure that fields 'deny', 'permit', 'mask' contain valid IP or are set to "(NULL)" value (if no ACL control is needed) If you have error message like : WARNING27221 acl.c: Unable to lookup '' NOTICE27221 chan_sip.c: Registration from '<sip:xxx@a.b.c.d:zzz>' failed for 'a.b.c.d' - No matching peer found http://www.voip-info.org/wiki/view/27221 http://www.voip-info.org/wiki/view/27221 be sure that field 'defaultip' is not null (set value to '0.0.0.0' if you don't need it).

Apr 07/09 Akan Nkweini Added 'lastms'. Without this I had the following error res_config_mysql.c:376 update_mysql: MySQL RealTime: Failed to query database. Check debug for more info.

Dec 03/08 Artem Asterisk 1.4.21.2 (on Debian) does not work if qualify is set and rtcachefriends=yes (which is default). qualify must be NULL or should not be in the table at all. Otherwise this error message will flood your log file/console: handle_response_peerpoke: Peer 'xyz' is now Reachable. Sept 18/08 caspar It seems like Asterisk 1.6.0 RealTime SIP does not work without the following fields:

defaultip defaultuser regserver regseconds mask fromuser fromdomain

May 14/08 arf_ Added 'subscribecontext' to the above as it's may be needed in some case (and it works a least with asterisk 1.4.18) Apr 15/08 bcnit Added 'defaultuser' to the above as it's needed in Asterisk 1.6. Jul 9/07 bcnit Note that 'regserver' has been added to the above this doesn't appear to be used by anything other than the initial call RealTime makes to clear the record, but including it gets rid of a WARNING on the console! Jun 8/07 bcnit If you are going to access the table above using MS Access and MyODBC, define port as: `port` mediumint(8) unsigned NOT NULL default '0' Or you'll have all sorts of problems trying to update rows! Jan 4/06 mhaynes I ran into problems using the Message Waiting Indicator with my Cisco 7960g phone using the

realtime system under Asterisk 1.2.0. Turns out you need to set the rtcachefriends=yes in the general context of your flat file sip.conf. Once this is done, MWI starts working as usual. Nov 9/05 hfwang Note: It seems that since asterisk 1.0.2RC1 there is 1 additional field for SIP accounts called 'fullcontact'. Added this field in the table above. Updated by: DHuang (3/16/05) Updated by: utdrmac - incominglimit and outgoinglimit are deprecated. Use Asterisk cmd SetGroup instead. http://www.voip-info.org/wiki/view/Asterisk+cmd+SetGroup Added setvar column

NOTE: The index created on the column 'name' is because RealTime does its SELECT query using that column everytime. That column must also be unique. You do not need every column listed above. If you wish, you can remove those columns you know you will never use. The columns in your tables should line up with the fields you would specify in the given entity declaration. If an entry would appear more than once, in the column it should be separated by a semicolon. For example, an entity that looks like: [foo] host=dynamic secret=bar context=default allow=gsm allow=ulaw could be stored in a table like this:

name

host

secret

context

ipaddr

port

allow

foo

dynamic

bar

default

127.0.0.1

4569

gsm;ulaw

You do not need to insert the ipaddr, port or regseconds information. These columns will be updated periodicaly by RealTime.

Testing

Throw some data into the above table and try to register an extension. The /var/log/asterisk/debug should give info on any problems. Realtime Caching... As of CVS-HEAD 3/16/05, if you enable RealTime caching in your sip.conf, Voicemail MWI works and so does 'sip show peers'. To do so, add "rtcachefriends=yes" to the general section of your sip.conf file. As the name implies, this caches the "RealTime" information from the database. As a result, there is a delay in updating some (if not all) fields in the SIP entry when you update the database. For instance, if you create an entry with a context = "context1" and Asterisk loads it from the database (perhaps the phone registered or tried to make a call), Asterisk holds on to that information as far as I can tell, indefinitely until a sip reload occurs. This also means that you will have to do a sip reload to clear out any entries. Removing them from the database does not seem to work. You can still add new entries though without reloading Asterisk. RealTime caching...isn't that an oxymoron anyways? :-) (Someone check to see if this affects IAX too, I don't have any IAX phones at the moment. - Flobi) (RealTime caching does affect IAX as well, works the same way. - Josh) Update : use "sip prune realtime PEERNAME" then "sip show peer PEERNAME load" to flush the peer and reload from db - (Voicemeup)

FreeSwitch
FreeSwitch is a full featured PBX capable of routing both Voice and SMS traffic. We use it to provide multi-modal applications that are capable of mixing voice, SMS, location (RRLP), and presence information. As of now, just voice and SMS are implemented. System Diagram In this diagram, Black links are network links (SIP) while Red links are filesystem lookups (sqlite3 db access).

Installation FreeSwitch, being a full-featured project outside the scope of OpenBTS, has it's own wiki detailing the installation and use of the system. You'll need two FreeSWITCH modules to interoperate with OpenBTS. Those are mod_python: http://wiki.freeswitch.org/wiki/Mod_python and mod_sms: http://wiki.freeswitch.org/wiki/Mod_sms Make sure to install (and configure!) those two modules.

Setup
OpenBTS to FreeSWITCH OpenBTS needs to route all outgoing voice and SMS messages to FreeSWITCH. FreeSWITCH provides multiple SIP endpoints, any of them will do. By default, the "internal" context is port 5060, while the "external" context is 5080. Due to a bug in FreeSWITCH, you have to specify the entire IP address. Localhost/127.0.0.1 WILL NOT WORK. To update the required fields, change the two following config fields in /etc/OpenBTS/OpenBTS.db to your local address (192.168.1.1 in this example). SIP.Proxy.Voice = 192.168.1.1:5060 SIP.Proxy.SMS = 192.168.1.1:5060 FreeSWITCH to OpenBTS OpenBTS has a very minimal SIP stack, so make sure that FreeSWITCH does not require any registration to receive SMS or Voice traffic. If you do not, FreeSWITCH will send 401 (Unauthorized) or 407 (Proxy Authentication Required) responses to your REGISTER/INVITE/MESSAGE messages. Doing this consists of two parts. First, you have to add the OpenBTS IP address to your access control list (in autoload_configs/acl.conf.xml). This allows any traffic from these IP addresses to be accepted without registration. In this example, we added them to the "domains" ACL that already exists: <list name="domains" default="deny"> <!--place your OpenBTS IP here --> <node type="allow" cidr="192.168.1.1/24"/> <!-- old stuff below... --> It's worth noting that you CANNOT use the "special" function of the domains ACL that scans all users with CIDR attributed and automatically adds them to the ACL. This doesn't work, as it assumes one IP address per user, a critical flaw when working with OpenBTS. Following that change, you also need to modify your sip profile to accept connections without authorization. If you are using the internal profile, this is in conf/sip_profiles/internal.xml. Uncomment the following line as follows:

<param name="apply-register-acl" value="domains"/> You'll need to set some variables to ensure that FreeSWITCH can communicate with the other services running in the OpenBTS suite. The file conf/vars.xml needs three items defined: The subscriber registry location, and smqueue's host and port. Add these to the end of vars.xml
<X-PRE-PROCESS cmd="set" data="openbts_db_loc=/var/lib/asterisk/sqlite3dir/sqlite3.db"/> <X-PRE-PROCESS cmd="set" data="smqueue_port=5063"/> <X-PRE-PROCESS cmd="set" data="smqueue_host=192.168.1.1"/>

Lastly, there are a few utility scripts we've written that should be made accessible to FreeSWITCH. These are located in (openbtsdir)/FreeswitchConfig/scripts/. Copy all of those to (freeswitchInstallDir)/scripts. Their functions are detailed below. Restart FreeSWITCH and your system should be receiving and handing OpenBTS traffic.

Using FreeSWITCH with OpenBTS Tools There are a set of scripts included in the install which provide basic functions for communicating with FreeSWITCH. These are generally accessible from both the dialplan and the freeswitch CLI. These are detailed here: OpenBTS_DB.py OpenBTS_DB allows freeswitch plans to engage with the subscriber registry. Note the use of quotations, freeswitch sometimes removes 's, so we use double quotes instead. The basic commands are used as Plan: API: <action application="python" data='OpenBTS_DB SQL_COMMAND"'/>

Example: <action application="python" data='OpenBTS_DB SELECT callerid FROM sip_buddies WHERE name="IMSI000000000000000"'/> <!-- _openbts_ret set to 11111111 > <action application="log" data="${_openbts_ret}

CLI: API: python OpenBTS_DB SQL_COMMAND

EXAMPLE: python OpenBTS_DB OpenBTS_DB SELECT callerid FROM sip_buddies WHERE name="IMSI000000000000000" prints 11111111 OpenBTS_Send_SMS.py OpenBTS_Send_SMS sends an encoded SMS message to smqueue (not OpenBTS!) for storage and eventual forwarding to the client. You are able to specify the target for the SMS (phone number), return number (arbitrary number) and the actual content of the message. Messages over 160 characters are truncated. Plan: API: <action application="python" data="OpenBTS_Send_SMS TARGET_NUM|RETURN_NUM|TEXT"/>

Example: <action application="python" data="OpenBTS_Send_SMS 1111111|1000|Hello from OpenBTS!"/> CLI: API: python OpenBTS_Send_SMS TARGET_NUM|RETURN_NUM|TEXT

Example: python OpenBTS_Send_SMS 1111111|1000|Hello from OpenBTS!

OpenBTS_New_User.py OpenBTS_New_User is a replacement for smqueue's "register" functionality. It inserts a new user into the subscriber registry. Plan: API/Example: <action application="python" data="OpenBTS_New_User"/> DOES NOT WORK IN DIALPLAN YET. Reads chatplan variables instead of inputting them. CLI: API: python OpenBTS_New_User USER|TARGET_NUM|PORT Example: python OpenBTS_New_User IMSI000000000000000|1111111|5062 OpenBTS_Parse_SMS.py OpenBTS_Parse_SMS munges an incoming SMS (from OpenBTS) into a format that FreeSWITCH can understand. This means it can only be run from a chatplan. Plan:
API/Example: <action application="python" data="OpenBTS_Parse_SMS"/> DOES NOT WORK IN DIALPLAN YET. Reads chatplan variables instead of inputting them.

This sets a number of chatplan variables, with most in Hex. "openbts_rp_message_type" : RP Message Type "openbts_rp_message_reference" : RP Message Reference "openbts_rp_originator_address" : RP Originator Address "openbts_rp_dest_address_type" : RP Destination Address Type "openbts_rp_dest_address" : RP Destination Address (SMSC) "openbts_tp_message_type" : TP Message Type "openbts_tp_message_reference" : TP Message Reference "openbts_tp_dest_address_type" : TP Destination Address Type

"openbts_tp_dest_address" : TP Destination Address (SMS target) "openbts_tp_protocol_id" : TP Protocol ID "openbts_tp_data_coding_scheme" : TP Data Coding Scheme "openbts_tp_validity_period" : TP Validity Period "openbts_tp_user_data" : TP User Data "openbts_text" : Message Content (Text) Examples There are example chatplans and dialplans in (openbts_root)/trunk/openbts/FreeswitchConfig/. Here are some snippets of techniques. Dialplan

Routing

<extension name="local_call">

<!-- openbts_db_loc set in vars.xml --> <condition field='${python(OpenBTS_DB SELECT name FROM sip_buddies WHERE callerid="${destination_number}")}' expression="IMSI\d{15}"/> <condition field='${python(OpenBTS_DB SELECT callerid FROM sip_buddies WHERE name="${username}"' expression="\d{7,10}"> <action application="set" data='target=${python(OpenBTS_DB SELECT name FROM sip_buddies WHERE callerid="${destination_number}")}' /> <action application="set" data='effective_caller_id_number=${python(OpenBTS_DB SELECT callerid FROM sip_buddies WHERE name="${username}"'/> <action application="bridge" data="sofia/internal/${target}@${domain}:${sip_received_port}"/> </condition>

</extension>

Chatplan

Parsing: This should be done at the header of your chatplan, to ensure these variables can be used inside of it <!-- set all the openbts variables --> <extension name="openbts" continue="true"> <condition field="to_user" expression="^smsc$"> <!-- first, parse SMS --> <action inline="true" application="python" data="OpenBTS_Parse_SMS"/> <!-- second, look up sender --> <!-- freeswitch eats 's, switch them up here -->

<action inline="true" application="python" data='OpenBTS_DB SELECT callerid FROM sip_buddies WHERE name="${from_user}"'/> <!-- result in _openbts_ret --> <action inline="true" application="set" data="openbts_callerid=${_openbts_ret}"/> </condition> </extension>

Echo <extension name="echo"> <condition field="openbts_tp_dest_address" expression="^9189$">

<action application="python" data="OpenBTS_Send_SMS ${openbts_callerid}|9189|${openbts_text}"/> </condition> </extension>

Callback: call a user back from an SMS'd number

<extension name="callbacks"> <condition field="openbts_tp_dest_address" expression="^919(\d)$"> <!-- bgapi lets us finish this without waiting for the originate --> <!-- the space between the args and the dest is important, for some reason --> <action application="set" data="api_result=${bgapi(originate {origination_caller_id_number=${openbts_tp_dest_address}}sofia/internal/${from}:${f rom_sip_port} ${openbts_tp_dest_address})}"/> </condition> </extension>

Forward: put at the bottom of the dialplan, catch all traffic that didn't hit and forward it to smqueue <!-- send any other messages onto smqueue --> <!-- reencode for now... though I'll probably write a "forward" script --> <extension name="forward"> <condition field="openbts_tp_dest_address" expression="^(.*)$">

<action application="python" data="OpenBTS_Send_SMS ${openbts_tp_dest_address}|${from_user}|${openbts_text}"/> </condition> </extension>

Registration <!-- register a user in the subscriber registry --> <extension name="registration"> <condition field="openbts_tp_dest_address" expression="^101$"/> <!-- is it a number? --> <condition field="openbts_text" expression="^\d{7,10}$">

<action application="python" data="OpenBTS_New_User"/> <action application="set" data="response_text=${_openbts_ret}"/> <!-- lookup new number --> <action application="python" data='OpenBTS_DB SELECT callerid FROM sip_buddies WHERE name="${from_user}"'/> <!-- text back the return value --> <action application="python" data="OpenBTS_Send_SMS ${_openbts_ret}|101|${response_text}"/>

</condition> </extension>

MultiBTS network
As your network matures, you may want to connect more than one concurrent OpenBTS system. This is easy to do. Basically, each OpenBTS node runs on a separate machine, then connected to centralized sipauthserve, PBX, and smqueue processes (which may or may not be running on the same machine.) Here, we document the configuration required for such a setup.

Initial Requirements Firstly, the "basic" install does not support secure, networked VoIP communications. Instead, you'll need to install either Asterisk Real-Time or FreeSWITCH. Secondly, you'll need to move each configuration file (e.g., OpenBTS.db) to the machine that will be running the associated process. Remember that there will now be multiple, different OpenBTS.db files, one for each BTS location. Also remember that ALL processes (except the PBX) expect their configurations in /etc/OpenBTS. System Diagram

Configuration You'll need to change the default configuration databases to point at the new machines running each server. In this example:

PBX (Asterisk)- 192.168.1.0:5060 smqueue - 192.168.1.0:5063 sipauthserve - 192.168.1.0: 5064 OpenBTS (1st BTS) - 192.168.1.1:5062 OpenBTS (2nd BTS) -192.168.1.2:5062

PBX Asterisk Fortunately, Asterisk does not need to be reconfigured unless it is accessing the subscriber registry over the network. FreeSWITCH The FreeSWITCH install needs to know the location of smqueue in order to forward SIP MESSAGEs. To do this, change (FS ROOT)/conf/vars.xml to the network location of smqueue: <X-PRE-PROCESS cmd="set" data="smqueue_port=5063"/> <X-PRE-PROCESS cmd="set" data="smqueue_host=192.168.1.0"/> smqueue /etc/OpenBTS/smqueue.db has numerous variables that need to be set to the new network locations of each service

Asterisk.address -> 192.168.1.0 The network location of the PBX SIP.myIP2 -> 192.168.1.0 The external-facing IP address of smqueue SIP.Proxy.Registration -> 192.168.1.0:5064 The location of sipauthserve

sipauthserve Fortunately, sipauthserve is a passive engine that does not need to know where any other services are located. OpenBTS Running multiple BTS's concurrently is a difficult task. Each BTS must not only be configured to know the location of the network services, but also configured to not interfere with their nearby BTS neighbors. Network Configuration Every OpenBTS install must be configured (at /etc/OpenBTS/OpenBTS.db) to the smqueue, sipauthserve, and PBX services. This can be done either with the sqlite3 client or via the OpenBTS].

SIP.Local.IP -> 192.168.1.1 (or .2) The external IP of the OpenBTS install. SIP.Proxy.Registration -> 192.168.1.0:5064 The IP/Port of sipauthserve SIP.Proxy.SMS -> 192.168.1.0:5063 The IP/Port of smqueue (or FreeSWITCH) SIP.Proxy.Speech -> 192.168.1.0:5060 The IP/Port of the PBX

BTS Configuration There are two types of BTS configurations needed to put together a network. First, a number of variables must be THE SAME for all BTSs on a network:

GSM.Identity.MCC The mobile country code GSM.Identity.MNC The mobile network code GSM.Identity.BSIC.NCC The network color code, must be unique from all other networks around you. GSM.CellSelection.NCCsPermitted The NCCs permitted by your BTS. Should include the above.

The following have to be DIFFERENT for each BTS.


GSM.CellSelection.BSIC.BCC The BTS color code. Each BTS should have a different color code. GSM.Identity.LAC The Location area code. Have to be unique for each BTS GSM.Identity.CID Cell ID, again unique per BTS.

Debugging It's pretty easy to get these wrong. For network configuration, use a tool like wireshark: http://www.wireshark.org to trace the traffic. This picture below gives an overview about the components used. The main hardware device is Ettus' Universal Software Radio Peripheral (USRP), connected via USB to a standard PC running the OpenBTS application and Asterisk. The RF RX part of the GSM access point consists of a simple ground plane antenna (triple leg) and a duplexer. The RF TX path is first boosted by about 25dB and then fed through the duplexer. The TX power is about 0 dB ERP.

Hardware

USRP The USRP is equipped with two 1800MHz daughterboards.

Amplifier We are using a 25dB power amplifier, thanks to Communications Systems Service GmbH!

Duplexer Kathrein Type No. 792 542 (1710-1785/1805-1880). Thanks to Kathrein!

Antenna The triple leg antenna (obvioulsy non professional .

Software OpenBTS Implementation of the Um Interface.

Asterisk:
A standard installation of Asterisk is required. OpenBTS uses Asterisk not only for handling VoIP calls, also for user authentication. Every mobile user has to be registered in the sip.conf with its particular IMSI. Test Setup Our test equipment consists of R & S FSP Spectrum Analyzer, R&S Universal Radio Communication Tester CMU 300, an Agilent E4433B ESGD Series signal generator, several cell phones (Siemens A60, Nokia 3310, Sony Ericsson K770i) and two Cisco 7940 VoIP Phones. Thanks to R&S for lending the CMU 300!

The internal quartz oscillator is by far not stable enough.

It works!

The old Siemens on the left indicates "CC 262 NC 09", which is our country and network code. Still displayed is the mobile providers branding "o2 - de".

More information : http://www.joshknows.com/gnuradio http://gnuradio.org/redmine/projects/gnuradio/wiki/UbuntuInstall http://gnuradio.org/redmine/projects/gnuradio/wiki/ReportingErrors http://ettus-apps.sourcerepo.com/redmine/ettus/projects/uhd/wiki https://wush.net/trac/rangepublic/wiki/n210Radio

Das könnte Ihnen auch gefallen