  

  













Internet to WSN configuration and access using 6LoWPAN

Master Thesis in Network Engineering

2014

Author: Arash Mokhtari Karchegani, Navid Firouzbakhsh

Supervisor: Tony Larsson

Examiner: Tony Larsson

_________________________________________

School of Information Science, Computer and Electrical Engineering

Halmstad University

PO Box 823, SE-301 18 HALMSTAD

Sweden

Internet to WSN configuration and access using 6LoWPAN

Arash Mokhtari Karchegani, Navid Firouzbakhsh

© Copyright Name(s) of author(s), 2014. All rights reserved.

Master thesis report IDE 1413

School of Information Science, Computer and Electrical Engineering

Halmstad University

_________________________________________

School of Information Science, Computer and Electrical Engineering

Halmstad University

PO Box 823, SE-301 18 HALMSTAD

Sweden

Preface

The current dissertation is written to fulfil the requirements for the Master of

Computer Network Engineering (60 credits) thesis at Halmstad University, Sweden.

First and foremost, we would like to express our sincere gratitude to our supervisor,

Prof. Tony Larsson for guiding and supporting us during this research. We would also like to thank Thomas Lithén for providing us with the necessary equipment for the implementation part of this thesis work.

Finally, we thank our families and friends who have been supporting us all the time we have been in Sweden.

Arash Mokhtari Karcheghani Navid Firouzbakhsh ii

Abstract

The Internet of Things mission is to connect any objects to the Internet, in order to provide the ability to access everything, everywhere. It will enable people to control and monitor their environment in a very convenient way. In order to fulfill the

Internet of Things mission, one idea is to wrap a non-IP based protocol stack in the objects equipped with sensors, actuators and computing resources to enable them to be connected to the Internet through a protocol translation gateway. An alternative and competing idea, is to embed the TCP/IP stack into such smart objects, enabling them to interact with the Internet seamlessly. However, in order to satisfy the Internet of Things needs such as scalability, interoperability and simplicity of configuration and management, the use of IP architecture for smart objects is of interest, since it has proven itself a highly scalable, interoperable and simple communication technology.

In particular, the new optimized Internet Protocol, IPv6, which is capable of providing any single object with a unique address, accompanied by many other great features such as plug-and-play and a real end-to-end connectivity, can offer great benefits to the Internet of Things. Nevertheless, most of the smart objects specially deployed in

Wireless Sensor Networks a subset of Internet of Things, are not able to adapt the large IPv6 packet because of their Link- Layer limitations. Hence, it is a quite challenging task for these devices to transmit an IPv6 packet. For this reason, the

Internet Engineering Task Force organization has offered an IPv6 over Low-Power

Wireless Personal Area Networks (6LoWPAN) solution in order to solve the IPv6 adaptability problem. This thesis presents the design and deployment of an IPv6based WSN using this solution. The result of this work is building a 6LoWPAN based on the Contiki OS. This WSN is able to send the measured environment temperature to a web server and control the status of a light through the Internet in a standard, scalable, and seamless way. iii

Contents

Preface .................................................................................................................................. iii

Abstract ................................................................................................................................ iii

1 Introduction .................................................................................................................. 1

1.1 Introduction ...................................................................................................................... 1

1.2 Motivation ......................................................................................................................... 2

1.3 Goal ...................................................................................................................................... 2

1.4 Thesis Structure .............................................................................................................. 2

2 Background .................................................................................................................... 5

2.1 The Internet of Things (IoT) ....................................................................................... 5

2.2 Wireless Sensor Networks (WSN) ............................................................................. 5

2.3 Smart Objects and its challenges ............................................................................... 5

2.4 Short-Range Wireless Standards ............................................................................... 7

2.4.1 IEEE 802.15.4 ........................................................................................................................ 7

2.4.2 ZigBee ....................................................................................................................................... 9

2.4.3 ZigBee IP (ZIP) ...................................................................................................................... 9

2.4.4 Z-Wave ..................................................................................................................................... 9

2.5 Introduction to IPv6 .....................................................................................................10

2.5.1 Protocol Overview ............................................................................................................ 10

2.5.2 Prefix Model for WSNs .................................................................................................... 12

2.5.3 Neighbor Discovery ......................................................................................................... 13

2.5.4 Stateless Address Autoconfiguration ....................................................................... 13

2.5.5 IPv6 capabilities ................................................................................................................ 14

2.5.6 Network Address Translation (NAT) ....................................................................... 15

2.5.7 IPv4 Interconnectivity .................................................................................................... 15

2.6 6LoWPAN .........................................................................................................................16

2.6.1 6LoWPAN Motivations ................................................................................................... 16

2.6.2 Header Compression ....................................................................................................... 17

2.6.3 Fragmentation Header ................................................................................................... 18

2.6.4 Mesh Header ....................................................................................................................... 19

2.7 The Contiki Operating System ..................................................................................20

2.7.1 Contiki Protothread ......................................................................................................... 21

2.7.2 Contiki Kernel .................................................................................................................... 21

2.7.3 Contiki communication stacks .................................................................................... 22

3 6LoWPAN Experiment ............................................................................................ 26

3.1 6LoWPAN Border Router (6LBR) ............................................................................27

3.2 Contiki application .......................................................................................................28

3.3 Tunnel Broker ................................................................................................................29

3.4 Web Server ......................................................................................................................30

4 Analysis of 6LoWPAN experiment and background findings ................... 33

4.1 Gateway issues in Wireless Sensor Networks ....................................................33

4.1.1 Complexity ........................................................................................................................... 33 v

4.1.2 Lack of flexibility & scalability..................................................................................... 34

4.2 Benefits of 6LoWPAN ...................................................................................................34

4.2.1 Interoperability ................................................................................................................. 34

4.2.2 6LoWPAN is Flexible ....................................................................................................... 35

4.2.3 6LoWPAN is scalable ....................................................................................................... 35

4.2.4 6LoWPAN is standardized ............................................................................................ 36

4.2.5 Ease of configuration and management .................................................................. 36

4.2.6 6LoWPAN is secure .......................................................................................................... 36

4.2.7 6LoWPAN is lightweight ................................................................................................ 36

4.2.8 Major differences between 6LoWPAN and the alternatives ........................... 37

5 Conclusions ................................................................................................................. 39

Appendix A ......................................................................................................................... 40

Appendix B ......................................................................................................................... 43

Bibliography ...................................................................................................................... 52

Chapter 1

1 Introduction

1.1 Introduction

Humans have always had the desire to make their lives better and easier. This desire, accompanied by an enthusiasm for discovering new things, made the curious human come up with great new ideas. The idea of connecting objects to the Internet is considered as a very promising idea, enabling a higher quality of life. Today, among different well-known wireless networks, the Wireless Sensor Network (WSN) has an interesting potential to develop this idea, since it takes full advantage of many features like low energy consumption, mobility, ease of use, and scalability.

In recent years, there has been a huge interest in using wireless technology with objects equipped with sensors and actuators in order to monitor and control homes, factories, offices, and even outdoors via the Internet. In order to fulfil these goals, it is advocated to embed the TCP/IP stack [1] which has been renewed by the new features of IPv6 (such as the address space and plug-and-play) in the objects and enable them to be routed through the Internet. Therefore, a new area of study, The

Internet of Things (IoT), emerged. The IoT provides the possibility of accessing everything, everywhere. With IoT, it is possible to monitor and control the environment by smartphones, tablets, laptops and so on through the Internet. WSN which is considered to be subset of IoT utilizes a wide variety of different wellknown technologies such as IEEE 802.15.4, IPv6 and 6LoWPAN to bring the dream of accessing everything, everywhere, into a reality. In fact, this is the IPv6 address space that can provide every single object with a unique identification and enable them to be routed through the Internet in a simple, scalable, efficient and reliable way. However, it is quite a challenging task to wrap a TCP/IP stack into the resource-constrained smart object devices like sensor nodes ( also known as motes ) since they were not originally designed for these types of devices. In particular,

IPv6 requirements are too heavy to be met by these kinds of devices, working with

IEEE 802.15.4 MAC and Physical layers. Thus, it is not possible for 802.15.4 devices to adapt the large IPv6 packets, directly. Therefore, the Internet Engineering Task Force

(IETF) offered 6LoWPAN (IPv6 over Low-Power Wireless Pan Area Network) in

RFC as an intermediate layer which is placed between the network layer and the data link layer to resolve the adaptability problem. 6LoWPAN makes the transmission of the IPv6 over IEEE 802.15.4 networks possible. By taking the advantages of 6LoWPAN, any IEEE 802.15.4 devices are able to receive and process

IPv6 packets.

However, in addition to the IP architecture, there are other non-IP based alternatives such as ZigBee and Z-Wave that are still popular to integrate WSN with the Internet.

1

Internet to WSN configuration and access using 6LoWPAN 2

1.2 Motivation

Recently, the Internet has fundamentally changed how we communicate, do business, retrieve information, entertain and educate ourselves. From a few connections made up of ARPANET in 1969, the Internet has evolved to become the

Internet of Things with billions of connected devices. We believe that amazing things will happen when we connect daily used devices to the Internet. For instance, your health care provider can monitor vital signs remotely through sensors worn in your clothes. Your alarm will wake you 10 minutes before, when the traffic is congested.

Your home will adjust its temperature according to the weather. Your sprinklers will skip watering when it is raining.

So far, Wireless Sensor Networks deployed proprietary protocols which would make it difficult to integrate smart objects with the Internet. Fortunately, the emergence of a single common standard called 6LoWPAN along with memory-efficient embedded operating systems such as Contiki provide smart object networks with the opportunity to benefit from IPv6 capabilities and be connected to the Internet in a more convenient and useful way than it was before. In this thesis a 6LoWPAN network is implemented to be deployed, for example in a smart home application.

However, when it comes to protocol development, always, security issues have been chronically a big challenge. For example, the Internet Protocol security (IPsec) whose use is mandatory in IPv6 was originally designed for non-resource-constraint devices. Therefore the use of IPsec is greedy for resource-constraint devices used in

6LoWPAN. Moreover, the secure version of Neighbour Discovery protocol (SeND) is not compatible with 6LoWPAN yet. Thus, 6LoWPAN security retains significant challenges which should be studied to find suitable solutions. However, this field of study is beyond the scope of this thesis.

1.3 Goal

In this thesis, we have chosen to investigate the IETF standard solution for connecting WSN to the Internet using IPv6 in order to control and monitor the environment. The goal of this thesis is to configure a 6LoWPAN network using the

Contiki embedded operating system and provide a standard monitoring and controlling application. Another goal is to show how to write an application in

Contiki OS and how to install and configure a deployment-ready 6LoWPAN Border

Router called 6LBR on the Raspberry Pi to connect 6LoWPAN devices to the Internet for data collection and monitoring purposes. Moreover, we investigate advantages and disadvantages of 6LoWPAN technology. The major differences between solutions will be mentioned as well.

1.4 Thesis Structure

This thesis structure is divided into 5 chapters. Chapter 1, “introduction”, gives

3

Chapter 1. Introduction general information about the area, states problems, defines the thesis goals accomplished in this thesis and specifies the thesis structure. In Chapter 2,

“background”, we briefly talk about the Internet of Things and its applications along with the important technologies being used in this field. In Chapter 3, we explain the configuration of our 6LoWPAN network and how it is connected to the Internet.

Chapter 4 argues the importance of the IP architecture in smart object networks.

Finally, in the last chapter, “Conclusion”, we summarize the advantages of

6LoWPAN.

Internet to WSN configuration and access using 6LoWPAN 4

Chapter 2

2 Background

2.1 The Internet of Things (IoT)

The Internet of Things is a paradigm that aims to provide any objects with a unique identification address and enable them to be connected to the Internet. These objects are usually expected to either capture data from their surroundings or send them to a database to be analysed or to perform a certain action, according to an order sent from a remote host. This fact makes the use of IPv6 necessary because of its plentiful capabilities such as its large address space or the ability to provide end-to-end connectivity. We will talk about IPv6 benefits later in chapter 4. Also, Wireless

Sensor Networks which deploy sensors and actuators play a significant role in contributing to IoT. There is more information regarding WSN in the next section.

Therefore, the Internet of Things is composed of a large set of control and monitoring applications such as smart homes, smart cities, smart agriculture, smart metering and so on. Thus these applications include a wide variety of different markets from individuals, families to industry.

2.2 Wireless Sensor Networks (WSN)

A Wireless Sensor Network is deployed to control and monitor the environment. It usually consists of a number of smart sensing nodes which capture data from the environment, sending it to a sink to be processed and analysed. The nodes may need to communicate with each other through their wireless interface and send the packets over multi-hop radio hops in order to deliver captured data to the sink. WSN applications are classified as military, health care, home automation, smart Metering, smart cities, smart agriculture, industrial controls and so on. There are several standards used in WSN field IEEE works on the physical and MAC Layer; The

Internet Engineering Task Force (IETF) focuses on the network layer. IEEE 802.15.4 physical and MAC layer, ZigBee, Z-Wave and 6LoWPAN are the predominant standards used in WSN.

2.3 Smart Objects and its challenges

Smart Objects applies to small computers equipped with sensors and/or actuators along with communication devices embedded into objects such as thermometers, light switches, car engines and many other daily used devices. Until recently, Smart

Object communication capabilities were limited to RFID tags, but the new generation of them is provided with bidirectional wireless communication and sensors.

5

Internet to WSN configuration and access using 6LoWPAN 6

The main components of smart objects include CPU (8-16 or 32 micro-controllers), memory and a low-power, low-rate wireless communication device (mostly IEEE

802.15.4). These devices typically capture real-time data such as temperature, pressure, energy measurements. Today, Smart Objects are widely used in Wireless

Sensor Network applications to monitor and control an environment. However, the smart object networks are faced with important challenges as follows:

Scalability: smart object networks [2] deployed in IoT applications usually consist of a large number of nodes. The current smart object systems have thousands of nodes and they are likely to develop into systems with hundreds of thousands or even millions of nodes. Some applications such as smart homes and smart grids formed with a small number of nodes may desire to expand over time in order to add more capabilities to the system. Thus, developers should be provided with enough critical mass to be able to scale the system up without scrapping the whole network and starting from scratch. For these reasons, scalability is considered to be an important challenge for IoT applications. The goal is to ensure that capabilities such as addressing, routing and management mechanisms are supported by the smart object network architecture.

Interoperability and standardization: Because of the existence of a wide variety of different applications and communication technologies, it is desirable to use a common standard network layer to provide interconnectivity among devices using different communication mediums. Standardization provides the opportunity to freely choose from a wide range of vendors.

Configuration and management: As mentioned above, the number of nodes deployed in IoT applications is usually huge. Therefore it is critical to provide management and configuration mechanisms that allow the network administrator to manage such large networks without manual configuration of each node.

Security and privacy: Security is a chronic issue when it comes to protocol developments; when designing security solutions for smart objects, the resourceconstrained characteristics of these devices should be taken into account. Smart objects suffer from limited computational abilities such as the small amount of memory and the lack of power supply.

Low cost: Since smart object networks are usually implemented by deploying a large number of nodes, even a small reduction in per-device costs could dramatically reduce the cost of the whole system. The cost constraints are considered as one of the factors that can limit the memory size and computational power.

Low-power consumption: Another smart objects challenge is power limitation, since they are often equipped with batteries that cannot be easily replaced or recharged.

Hence, the power consumption of smart objects must be as low as possible to accomplish the optimum battery lifetime.

In this thesis we argue that the IP architecture, in particular, the IPv6, can meet these challenges simultaneously.

7

2.4 Short-Range Wireless Standards

Chapter 2. Background

2.4.1 IEEE 802.15.4

IEEE 802.15.4 working group was formed in 2000 to work on a standard for wireless personal area network. The working group released IEEE 802.15.4 standard [3] including physical and MAC layers for low-power Personal Area Networks (LR-

WPANs). The other higher layers are not defined in this standard; however,

6LoWPAN or ZigBee can be built on the top of the MAC and physical layer to create a wireless embedded Internet.

Figure 2.1: The topologies used in IEEE 802.15.4 networks

IEEE 802.15.4 Topologies

The IEEE 802.15.4 standard includes two device types: full-function devices (FFDs) and reduced-function devices (RFDs). FFDs can operate in three modes including a

PAN coordinator, coordinator or a device. Reduced Function Devices work only as an end device responsible for very simple applications such as a light switch. IEEE

802.15.4 LR-WPANs are based on either star or peer-to-peer topologies. In a star topology all devices communicate only with a single central node known as a PAN coordinator, whereas in peer-to-peer topologies devices can communicate with any other devices present in their coverage area. Figure 2.1 depicts the topologies used in

IEEE 802.15.4 networks.

7

Internet to WSN configuration and access using 6LoWPAN

IEEE 802.15.4 Physical (PHY) layer

8

The IEEE 802.15.4 Physical (PHY) layer handles the following tasks: activation and deactivation of radio transceiver, transmission and reception of PHY protocol data units (PPDU) over physical medium, clear channel assessment (CCA), channel selection, energy detection in the present channel and link quality indicator (LQI).

Different frequency bands, modulations and supported data are shown in Table 2.1.

Table 2-1: IEEE 802.15.4 physical layers

Physical Layer

(MHz)

868/915

868/915

868/915

2450

UWB

2450

(CSS)

Frequency Band

(MHz)

868 – 868.6

902 - 928

868 – 868.6

902 - 928

868 – 868.6

902 - 928

2400 – 2483.5

250 – 750

3244 - 4742

5944 - 10234

2400 – 2483.5

Modulation

BPSK

ASK

O-QPSK

O-QPSK

BMP-BPSK

Bit rate

(kb/s)

20

40

250

250

Description

BPSK: Binary phaseshift keying

ASK: Amplitude phase-shift keying

100

250

O-QPSK: Offset quadrature phaseshift keying

250

851, 110,

6810 &

27240

BPM: Bust phase modulation

UWB: Ultra-wide band

1000

DQPSK

250

CSS: Chirp spread spectrum

DQPSK: differential quadrature phaseshift keying

780

780

950

950

779 - 787

779 - 787

950 - 956

950 - 956

O-QPSK

MPSK

GFSK

BPSK

250

250

100

20

MPSK: M-order phase-shift keying

GFSK: Gaussian frequency-shift keying

IEEE 802.15.4 MAC Layer

The IEEE 802.15.4 MAC layer is mainly responsible for the following tasks: transmission of MAC frames over PHY layer, beacon management, PAN association and disassociation, deploying CSMA-CA mechanism for channel access, validation of frames and supporting device security. The MAC frame header is depicted in

Figure 2.2.

9

Chapter 2. Background

Figure 2.2: IEEE 802.15.4 data frame

2.4.2 ZigBee

ZigBee Alliance established in 2002 to design a non-IP protocol stack called ZigBee in order to be used for monitoring and controlling home appliances over IEEE 802.15.4 networks. In fact, the ZigBee standard introduces only an application, security, and network layer for IEEE 802.15.4 based devices [4]. Although ZigBee provides a secure, low-power, low-cost, easy-to-use wireless communication which can meet the WSN application requirements; it is not compatible with IP architecture. ZigBee

Networks can communicate with the IP network only through a protocol translation gateway, whose responsibility is to translate the ZigBee protocols to the Internet

Protocol. However, the gateway imposes problems such as complexity, lack of flexibility and scalability. We will talk about these problems in section 4.1.

2.4.3 ZigBee IP (ZIP)

In 2009, it was announced that the ZigBee alliance was working on another protocol that would be able to support IP as its communication mechanism. The goal was to extend the use of IP over the resource constrained devices. Eventually, the alliance defined an open standard-based specification called ZigBee IP (ZIP) to bring an IPv6 network protocol over IEEE 802.15.4 wireless mesh networks without the need for gateways. ZIP was designed specifically to support ZigBee Smart Energy standard and was released at the time of writing this thesis. ZIP provides cost-effective and energy-efficient wireless mesh networks based on the IETF standards. For example, it supports 6LoWPAN for header compression, RPL for mesh routing and TLS/SSL-

B for security.

2.4.4 Z-Wave

Z-Wave is another low-power wireless technology which was mainly developed by

Zen-Sys in 2005 for smart home applications. Z-wave is not an IP-based technology and has implemented its own protocol stack. Its radio waves can pass through walls, doors and floors. Z-Wave provides the plug-and-play mechanism, leading new devices to be connected to the network without manual configuration. It also provides a development kit to give the possibility of developing Z-Wave based

9

Internet to WSN configuration and access using 6LoWPAN 10 products by the use of API. Z-Wave devices can be connected to the Internet through a protocol translation gateway since it does not support IP.

2.5 Introduction to IPv6

The Internet protocol (IP) is the principal protocol in the TCP/IP protocol suit which was originally defined by Vint Cerf and Robert Kahn in an IEEE journal under the title “A Protocol for Packet Network Interconnection”[4] about 30 years ago. IP is considered as the network layer which provides the necessary functions to deliver a packet from one node as a source to another as a destination (both with an identification address) across a network composed of an unknown number of nodes.

2.5.1 Protocol Overview

IPv4

As mentioned before, IPv4 is the updated version of IP and defined in RFC 791 [5]. It uses 32 bits for address space which provides up to 2

32 addresses. IPv4 has successfully dominated the Internet over 30 years and is still being used. However, by emerging new technologies like Wireless Sensor Networks and IP embedded devices, IPv4 is being finished because of its address space limitation (providing only

32-bit addressing space) and does not seem to be able to meet the Internet of Thing’s challenges. In the beginning of IPv4 existence, no one imagined that the Internet one day will erode the power of its 32-bit address space. However, IT experts predict

IPv4 exhaustion will happen soon. It has been estimated by cisco that over 50 billion objects will be connected through the Internet of Things by 2020.

IPv6

In response to IPv4 address exhaustion, IETF, whose mission is to make the Internet work better, started to work on another generation of IP. The result was offering

Internet Protocol Version 6 (IPv6) defined in RFC 2460[6]. IPv6 is considered to be the successor of the old version (IPv4) because of its large address space and improved features. IPv6 address space uses 128 bits that makes up to 2

128 addresses available.

IPv6 Header

The IPv6 header shown in the figure 2.3 is simplified and includes a fixed header size

(40 bytes); however it supports the extension headers which may be added to the fixed header to provide features such as more efficient packet forwarding, authentication and mobility.

11

Chapter 2. Background

Figure 2.3: IPv6 datagram header

IPv6 addressing

As mentioned before, an IPv6 address includes 128 bits that provides 2

128 addresses.

The IPv6 address is based on x:x:x:x:x:x:x:x format, where x is a 16-bit hexadecimal.

An example of IPv6 could be 1236:1542:26B1:AC14:0123:1411:4422:3233. The 128-bit address is generally divided into two main portions. The first 64-bit portion known as network prefix to identify the network address and the second 64-bit portion known as interface identifier (IID) to identify the host address. The IID is derived either from a 64-bit IEEE EUI-64 (extended unique identifier [EUI-64]) which is assigned by the manufacturer of the device or a dynamically assigned 16-bit short link-layer address. The former is globally unique, while the latter is unique within the LoWPAN. The IPv6 address types are defined in RFC 4291[7] and are categorized as the following:

Unicast: is used when the packet should be delivered to one interface. Unicast addresses include three types, as follows:

Link-local address: Link-local addresses are used by IPv6 nodes when communicating with neighboring nodes on the same link. Link-local addresses are locally unique and use fe80::/10 prefix.

Site-local address: Site-local addresses are like private addresses in IPv4. They are used inside a site without the need for a global prefix.

Global address: IPv6 global addresses are like IPv4 public addresses. IPv6 global addresses are globally routable on the Internet. Typically, the network prefix of a global IPv6 address consists of a 48-bit global routing prefix

(typically hierarchically structured) and 16-bit Subnet ID (link identifier).

11

Internet to WSN configuration and access using 6LoWPAN 12

Multicast: is used when the packet should be delivered to multiple interfaces.

Anycast: is used when the packet should be delivered to the closest of multiple interfaces (according to the routing table in use).

2.5.2 Prefix Model for WSNs

An easy way of constructing a 128-bit IPv6 address is to attach a 64-bit prefix with a

64-bit IID address. The former is provided by an edge router in the LoWPAN and the latter is assigned by the manufacturer of the IPv6 device. This manner enables a node to obtain an IPv6 address. The internet protocol puts some restrictions on how IPv6 interfaces of the nodes are configured with IPv6 addresses. The following, describe how IPv6 addressing is constrained:

1. Each node must obtain a link-local IPv6 address which is unique within the

LoWPAN. The Stateless Address Auto-configuration mechanism is responsible for setting the IPv6 addresses for the IPv6 devices. This mechanism will be discussed later in section 2.5.4.

2. There should be a direct mapping between the link-layer address of a node and its IPv6 IID portion. It allows nodes to resolve network and link layer addresses without any communication or address resolution caches

3. The nodes must share a global prefix provided by the Edge Router to reduce header overhead and memory requirements for forwarding and routing.

Interface Identifier (IID)

6LoWPAN devices are required to derive the IID (host) portion from either IEEE

802.15.4 link-layer 64-bit or 16-bit addresses. The former makes the address globally unique and the latter makes it unique within the LoWPAN. Attaching the IID to the

64-bit network prefix provides a unique IPv6 address. While using this manner to form an IPv6 address is a convention for many link layers, it is obligatory for

6LoWPAN which relies on Neighbor Discovery to construct an IPv6 address.

Neighbor Discovery will be described in section 2.5.3.

Global Routing Prefix

The IPv6 prefix which specifies the first 64-bit of the IPv6 address is provided by the edge router of the 6LoWPAN and is distributed to the all nodes within the LoWPAN.

Using a shared prefix in the same LoWPAN means that they are able to communicate with each other only by the means of their link-layer addresses.

However, in order to communicate with networks external to the LoWPAN they need to use their shared prefix. Using the common prefix within the LoWPAN exempts them from being carried in the packet header because the nodes agree on what the same prefix is. This leads the packet size to be reduced down to 8 bytes

13

Chapter 2. Background when the IID is obtained out of the IEEE EUI-64 and only 2 bytes when the IID is formed from the 16-bit short link-layer address. As a result, less memory space is used for routing and forwarding within the LoWPAN.

2.5.3 Neighbor Discovery

The Neighbor Discovery (ND) protocol, defined in RFC 4861, plays a significant role in bootstrapping an IPv6 network. Neighbor Discovery is used by the IPv6 nodes in the network to:

Find out their neighbor link-layer address on the same link.

Discover the reachable routers in the LoWPAN.

Distribute the network prefix address to the nodes within the LoWPAN

Construct their IPv6 address through Stateless Address Auto-configuration

ND Messages

According to RFC 4861, each Neighbor Discovery message is a type of ICMPv6 message. Neighbor Discovery messages are: Neighbor Solicitation (NS), Neighbor

Advertisement (RA), Router Solicitation (RS), Router Advertisement (RA) and

Redirect messages.

Neighbor Solicitation: A node sends this message to the neighboring nodes which is on the same link in order to determine their Link-Layer addresses.

Neighbor Advertisement: This message is used in response to the NS message and contains the Link-Layer information of the sender.

Router Solicitation: RS are sent by the nodes to the routers in the network in order to obtain the network information and the prefix addresses from the routers faster.

Router-Advertisement: RA contains routing information such as prefix information,

MTU and hop limit. RAs are sent either periodically or on demand in response to the

RS messages.

2.5.4 Stateless Address Autoconfiguration

IPv6 Stateless Address Autoconfiguration (SAA) defined in RFC 4862[8]. SAA is a mechanism aimed at configuring a unique IPv6, automatically. It is formed based on the interface identifier (IID) which is derived from link-layer addresses and the network prefix received from the router. In section 2.4.3 we explained how an IID is created. In SAA the 64-bit IID is attached to a 64-bit prefix address advertised by the router to form a 128-bit IPv6 address. The IPv6 address created this way goes through the following steps:

Tentative address: this address is not being assigned because the uniqueness of the address has not been verified yet. They are only used for Duplicate Address

Detection (DAD).

13

Internet to WSN configuration and access using 6LoWPAN 14

Preferred address: this address is allowed to be assigned to an interface with a certain life time and considered as a unique IPv6 address.

Deprecated address: Deprecated address is still a valid address but it will expire soon. This address should not be used as a source address unless it is hard to switch to a new address.

Valid address: a valid address is either a preferred or deprecated address. This address may exist in either the source or destination address of the packet.

Invalid address: Invalid address is an address whose lifetime has expired. This address is neither assigned to any interfaces nor used as a source or destination address of the IPv6 packets.

2.5.5 IPv6 capabilities

Scalability: as we noted before, the main feature of IPv6 is its extremely large address space. IPv6 extended the address size from 32 bits in IPv4 to 128 bits.

Theoretically, the 128-bit address provides 2

128

~ 10

39

possible addresses. Since this large address space can provide every square meter of the Earth surface with

655,570,793,348,866,943,898,599 it is hard to imagine that the IPv6 addresses will be consumed one day. Therefore, we can be sure that every single object can be provided with a unique address. Moreover, IPv6 eliminates the necessity of NAT since it provides a huge number of unique addresses.

In section 4.3.2 we discuss how NAT can cause problems for some IoT applications.

Plug-and-Play: IPv6 offers the “plug-and-play” mechanism that helps the devices to derive their own address independently and without any manual configuration or intervention from an administrator. Plug-and-Play relies on the Neighbour

Discovery (ND) protocol and makes the new node join the network automatically.

The plug-and-play capability enables IPv6 nodes to move between more than one

LoWPAN at the same time.

Real-time applications: IPv6 supports real-time traffic well since “labelled flows” is included in its specifications. This mechanism enables the router to realize the endto-end flow to which packets belong. This is similar to the mechanism provided by

Multi-protocol Label Switching (MPLS), but it is intrinsic.

Optimized protocol: IPv6 removes the obsolete characteristic of IPv4 which leads to better internet protocol.

Security: IPv6 includes security in its specifications such as payload encryption and authentication of the source of the communication. It calls for end-to-end security, with built-in, strong IP-layer encryption and authentication (embedded security support with mandatory IP Security [IPsec] implementation).

15

Chapter 2. Background

Mobility: IPv6 provides a more enhanced and efficient mobility mechanism which is vital for mobile networks. Mobile IPv6 as described in RFC 3775[14] is now being deployed.

2.5.6 Network Address Translation (NAT)

The Network Address Translation mechanism defined in RFC 1631[13] has been offered to solve the IPv4 address space exhaustion problem. NAT allows the use of one public address to connect a private IP network to the Internet. It translates all the private or internal IP addresses of the nodes inside the local network into a single public IP address in order to enable nodes with a private address to access the

Internet. In fact, the NAT device captures each transmitted packet and rewrites the source IP address and portions of the transport layer information. This operation requires rebuilding the protocol headers and recalculating the error detection checksum in both the IP and transport layer headers. These operations are more complicated than simple IP routing. The negative aspects of NAT can be summarized into one fact. NAT breaks the end-to-end principle of the Internet.

NAT failure causes the whole system to crash: when a NAT fails all the traffic through the NAT stops. Most of these issues occur because NATs maintains states in the network between end points in order to address mapping. This is as opposed to routers that can recover quickly when a failure happens. When a router recovers, the paths can be recomputed fast and the packets can be routed again. On the other hand, NATs are not able to reroute packets toward their destination, since the address translation maps may change when a failure occurs.

Certain peer-to-peer Applications, may not be able to communicate with each other through NAT. This is especially true for smart object networks. NAT hides nodes with private addresses and causes them not to be reachable globally. Of course, this problem can be addressed by deployment of NAT traversal techniques such as

Application Layer Gateways (ALG). However, such techniques may be cumbersome to manage since they would not work without additional software updates on NAT devices.

The purpose of listing the drawbacks of NATs is to highlight that NAT is not a “free” solution. IPv6 address space eliminates the necessity of using NAT and brings the real end-to-end connectivity in place.

2.5.7 IPv4 Interconnectivity

Nowadays IPv6 is becoming much more popular across the Internet. Although IPv4 is still dominating the Internet it will also play its significant role in the following years since there are lots of IPv4-based networks connected to the internet. This matter will present a problem for our 6LoWPAN which is naturally IPv6-based, to be connected to the Internet. The following mechanisms provided by IETF enable communication between IPv6 networks over an IPv4 infrastructure:

15

Internet to WSN configuration and access using 6LoWPAN 16

Configured-tunnelling: In this method IPv6 packets are encapsulated within IPv4 headers and able to be traversed over IPv4 infrastructure. To send IPv6 packets through the IPv4 Internet it is required to create (virtual) point-to-point tunnels at the end points across the IPv4 network. By the use of this method, a router or a host takes the advantage of the tunnels to obtain global IPv6 prefixes. Configuredtunnelling is considered to be a very useful manner to enable Simple LoWPANs and

Extended LoWPANs to communicate through IPv4 networks. This method is also known as IPv6-over IPv4 tunnelling.

Automatic-tunnelling: This method works like Configured-tunnelling but with a little bit of difference. In this method a well-known router which is one end-point of the tunnel has been already configured on the Internet to enable IPv6 nodes in the

6LoWPAN to connect the IPv6 Internet through IPv4 Internet without needing an explicit setup. The other end-point is a router or a host.

Simple LoWPAN: The Edge Router in the LoWPAN is configured to set up a tunnel to a known router, known as a tunnel broker. The Edge router acquires a global IPv6 prefix through the created tunnel, then the Edge Router distributes the Prefix to the whole LoWPAN.

Extended LoWPAN: Similarly, in this case the local IPv6 router also builds a tunnel towards the well-known router. The Router will receive a global prefix via the tunnel, configure its interface with that prefix and then send it over the backbone link to the Edge router. Again, the Edge Router is able to propagate the Prefix to its

LoWPAN.

2.6 6LoWPAN

6LoWPAN is a set of standards which enables the transmission of IPv6 packets over

IEEE 802.15.4. 6LoWPAN has been offered by the Internet Engineering Task Force

(IETF) to meet IPv6 requirement for Low-Power Wireless Personal Area Networks.

.In 2007 the 6LoWPAN IETF working group defined RFC 4919 [9] which describes an overview, detailed assumption and goals of standardization. The working group later defined RFC 4944 [10] which specifies the 6LoWPAN format and functionality.

6LoWPAN not only fulfils the IPv6 requirements, but it also supports the mechanisms to obtain a globally unique IPv6 address automatically (using Stateless

Address Auto-configuration).

2.6.1 6LoWPAN Motivations

The present Internet protocol requires a minimum Maximum Transmission Unit

(MTU) of 1280 bytes for transmitting IPv6 packets; hence there is a big challenge for

IEEE 802.15.4 MAC layer which only provides 127 bytes frame size to transmit packets. In order to overcome this problem 6LoWPAN offers an adaption layer to perform the following functions:

17

Chapter 2. Background

Header compression: to compress the IPv6 header by eliminating the redundant information.

Fragmentation and reassembly: IPv6 packets are fragmented into multiple link-level frames in order to meet the minimum MTU requirement.

Layer-two forwarding: to support layer-two forwarding of an IPv6 packet.

The 6LoWPAN uses a header stacking format to support the adaption layer functions. The header stack may use the IPv6 header compression stack when compressing IPv6 header is needed. The Fragmentation header is used when the payload exceeds the size of IEEE 802.5.4 frame. Finally, the Mesh addressing header is used when packets have to traverse over multi radio hops using layer two forwarding mechanisms. The 6LoWPAN header stack may use all, some or none of the 6LoWPAN headers.

2.6.2 Header Compression

As previously mentioned, an IEEE 802.15.4 MAC layer has a payload size limitation for transmitting IPv6 packets because of its large header and data payload. The 40byte IPv6 header occupies about half of the IEEE 802.15.4 payload. Even if the data payloads are small enough and the need for the fragmentation is not urgent, the battery life time and the channel capacity limitations in LoWPANs makes it necessary to reduce the size of the IPv6 header. The IETF defined Stateless Header

Compression mechanisms in RFC [4944] to decrease only the link-local IPv6 headers size. Since the important role of 6LoWPAN is to deliver packets to/from networks external to the LoWPAN, RFC [4449] is not widely accepted. Therefore IETF offered an optimized mechanism in RFC 6282 [11] referred to as Context-Based Header

Compression, which relies on a shared context to compress both link-local and global

IPv6 header size. Context Based Header Compression is divided into two compression schemes: one for compressing the IP header (LoWPAN_IPHC) and the other for the next header (LoWPAN_NHC) which is optional. In this thesis, we only describe the former which is the usual case.

The LoWPAN_IPHC header consists of 13 bits, 5 of which are used by the rightmost bits of the Dispatch. The figure 2.4 shows the 2-byte LoWPAN IPHC base header structure including Dispatch. The base header may be followed by a 1-byte Context

Identifier Extension. The other uncompressed fields are carried in-line. In the best case, LoWPAN_IPHC amazingly allows compressing 40-byte IPv6 header down to 2 bytes for the link-local and 3 bytes for the non-link-local communications. In each case the base header is attached with a 1-byte Dispatch at the beginning, even when no header compression is performed.

The following sections show the LoWPAN_IPHC encoding format:

Dispatch: Is set to 011 for LoWPAN_IPHC compression.

17

Internet to WSN configuration and access using 6LoWPAN 18

Figure 2.4: The 2-byte LoWPAN IPHC base header

TF: This field represents the traffic class and flow label which are elided if the value is set to 0.

NH: If this field is set to zero then next header will be carried in-line.

HLIM: If it is set to 00 the Hop Limit will be carried in-line, otherwise compressed.

CID: If 1, the additional Context Identifier header will follow the IPHC header.

SAC: if set, Source Address Compression uses stateless compression, otherwise the context-based compression is used.

SAM: Specifies the mode of source address compression.

M: If set, the destination is Multicast.

DAC: If set, Destination Address Compression uses stateless compression, otherwise the context-based compression is used.

DAM: Specifies the mode of Destination Address Compression.

The LoWPAN_IPHC mechanism works based on a shared context. The RFC [6282] does not specify how the context is shared or what information is included in it. The explanation of how the context works is beyond the scope of this thesis. More information regarding the context is provided in RFC 6775[17].

2.6.3 Fragmentation Header

As stated before, one of the functions of the adaption layer is IP fragmentation. If the

IPv6 data payload does not fit into the IEEE 802.15.4 frame, it has to be split into small fragments according to the maximum frame size, to be able to be traversed over the IEEE 802.15.4 Link-layer. Unlike the ordinary IP fragments, 6LoWPAN fragments only include the IPv6 header attached to the initial fragment of the packet.

Each of these fragments obtains a fragmentation header which contains the following three fields: Datagram Tag, Datagram Size, and Datagram Offset. Datagram Size specifies the original payload size and enables the receiving node in order to reserve a buffer for the reassembly of the whole packet. Datagram Tag identifies the set of fragments which belong to a certain data payload. Internet protocol does not guarantee that the fragments are delivered in the correct order and the receiver may get them out of order. Therefore, a fragment offset which is always in 8-byte units is used to specify the offset value of certain fragments. Fragments are placed in the receiver buffer according to the offset value. The fragment with the lower value is positioned before the ones with higher value. This leads the fragments to be sorted

19

Chapter 2. Background

Figure 2.5: The 6LoWPAN fragmentation structure and reassembled in order with respect to the whole datagram (the original packet before being fragmented). The fragment offset in the first fragment header is always set to zero. If the last fragment offset is zero too, it means there is no need for fragmentation. The 6LoWPAN fragmentation structure is depicted in figure 2.5. The first fragment header is 4 bytes (because the offset field is not included) and the remaining fragment headers are 5 bytes.

2.6.4 Mesh Header

When transmitting of 6LoWPAN packets over multi radio occurs at layer 2 the Mesh routing (layer-2 forwarding) is required. Since mesh routing is reliant on layer-2 addresses (64-bit EUI-64 or 16-bit short addresses), there is one problem to solve: The link layer header only contains the source and destination addresses of the current layer-2 hop. Additionally, the forwarding node needs to know the Originator and

Final destination addresses, as well. The source and destination addresses are IEEE

802.15.4 link- layer addresses which indicate each end-points of the communication.

Because forwarding causes overwriting the final destination address by the address of the next hop and the originator address by the address of the node preforming forwarding, it is necessary to keep the originator and final destination’s link-layer address somewhere else. 6LoWPAN offers the Mesh header to address this issue.

The mesh header must always stand in the beginning of the header stacking format and includes three fields: Hop Limits, Source Address and the Destination Address.

The Hop Limit specifies the number of hops the packet is allowed to traverse. At each hop it is decremented by the forwarding node and when it reaches zero the frame is dropped and not forwarded anymore. The source and destination addresses are obviously the addresses of the current layer-2 hop. The mesh header size range is between 5 and 17 bytes depending on the link-layer addresses in use.

Routing and forwarding in 6LoWPAN

Packets often need to be traversed over multiple radio hops. 6LoWPan offers two routing mechanisms: Mesh-Under and Route-Over. While Mesh under routing

19

Internet to WSN configuration and access using 6LoWPAN 20 happens at layer two and forwards packets based on link-layer addresses, Route-

Over deals with the IP addresses to make routing decisions. Each mechanism has its own advantages and disadvantages.

One of the great advantages of Mesh Under is that at each hop there is no need to perform fragmentation and reassembly. That’s because the Mesh-Under mechanism attaches a mesh header to each fragment in the adaption layer. This header keeps end-to-end link-layer source and destination addresses. Therefore, the forwarding node can make the routing decision based on the information in the mesh header. As a result, the intermediate node is exempted from observing the layer three headers in order to check source and destination addresses. Another advantage of the Mesh

Under mechanism is that the fragments may be forwarded over different paths since the per-fragment routing decisions are made. Routing over different paths has shown reduction in energy consumption and memory usage. This is a great result for energy and memory constraint devices. However, Multipath forwarding may lead packets to be delivered out of order.

In contrast to Mesh-Under, Route-Over does not provide mesh headers for each fragment and the routing decisions are made based on the information in the IPv6 headers. At each hop, if the packet should be forwarded to another node , the forwarding nodes will have to check the next hop address in its IPv6 routing table. It makes the receiving nodes reassemble the IPv6 packet and then fragment the packet again to forward it to the next hop. It causes the intermediate nodes and generally the whole LoWPAN to suffer from the increase in energy consumption. This is considered to be the only drawback of the Route-Over mechanism.

Although Mesh-Under may be considered to be a better mechanism for forwarding packets, IETF does not work on this mechanism very much. Therefore, Mesh-Under has not become a standard yet. As a result, the Route-Over is used more often than

Mesh-Under.

2.7 The Contiki Operating System

Contiki is a popular open source, portable, multitasking operating system suitable for memory-constraint networked embedded platforms and wireless sensor networks. Contiki has been implemented in C programming language by Adam

Dunkels at the Swedish Institute of Computer Science (SICS). Contiki contains two communication stacks: uIP and Rime. The uIP is a small TCP/IP stack designed to provide the Internet connectivity. Rime is a lightweight communication stack designed to provide internal connectivity within a LoWPAN. The uIP includes a very small implementation of both IPv4 and IPv6 referred to as: uIP [15] and uIPv6

[16] respectively, Therefore, it provides both IPv4 and IPv6 communication. Contiki also supports 6LoWPAN to provide IPv6 connectivity. Later in this chapter we will discuss more about Rime and uIP communication stacks.

Along with the main features mentioned above, Contiki provides a novel memoryefficient mechanism called protothreads [12] to simplify event driven programming of

21

Chapter 2. Background memory-constraint embedded devices such as wireless sensor nodes. Protothreads are very lightweight stack-less threads without the per-thread stack overhead.

Currently, different companies around the world, such as Thingsquare and Watteco are taking advantage of the Contiki Operating System and its uIP communication stacks to do their projects.

2.7.1 Contiki Protothread

Protothreads are a new interesting stack-less type of thread that provides a conditional blocking wait statement, PT_WAIT_UNTIL(), designed to simplify eventdriven programming for severely memory-constrained devices by removing, or at least reducing, the number of state machines which usually make programs difficult to write and debug. PT_WAIT_UNTIL () evaluates a conditional statement to determine whether the executing function in the program should be blocked or continued. Obviously, if the conditional statement is evaluated as true, the executing function continues without any interruption, otherwise the program becomes blocked and jumps to the end of function.

Protothreads work is based on Local Continuations which have the responsibility of storing the protothreads state [12]. The state of the executing protothread function is defined according to the point where the function is currently executing. Local continuations [12] work with two operation modes: set and resume. Set operation stores the current position of the executing function that can be later accessed by the resume operation. Therefore, local continuations can be considered as a mechanism used by the protothreads function to change the normal execution flow of the program.

Protothreads starts with PT_BEGINS() and ends with PT_ENDS() statements and the conditional blocking wait statements such as PT_WAIT_UNTIL() can be declared in between. When the compiler reaches PT_WAIT_UNTIL(), if the condition is not satisfied then the protothread becomes blocked, the set operation is performed and the program jumps to the end of the function. In this case, the caller function will be informed that the protothread has not finished and whenever it is invoked again the program can jump to the point which was previously stored by the set operation. In case the condition is met the function continues executing. The advantage of this way of programming is that the programmer will be able to realize which statements have the potential to be blocked.

2.7.2 Contiki Kernel

Before introducing Contiki Kernel and explaining how it works, we need to get familiar with process concept first. All the programs in Contiki are considered to be processes. A process is a piece of code executed by the Contiki OS. Process structure includes information about each process such as the process name, the process state, a function pointer that points to the protothread function and the protothread which contains its local continuation. In Contiki all the processes are written as

21

Internet to WSN configuration and access using 6LoWPAN 22 protothreads which are run on top of the event-driven Contiki kernel. It means the process is invoked whenever an event occurs. An event can be a message received from another process, a timer event, a signal from the pressed button, a notification from a sensor or any other kind of event in the system.

When a protothread in a process performs a conditional statement like

PT_WAIT_UNTIL(), the program will not continue to execute until either another process posts an event pointing to it or the protothread is polled by the kernel before executing the condition statement. Process structure includes information about each process such as the process name, the process state, a function pointer that points to the protothread function and the protothread which contains its local continuation.

Moreover, Contiki provides powerful libraries for timers. The timers usually play an important role in the majority of applications. These libraries make it possible for processes to set a timer.

2.7.3 Contiki communication stacks

The Contiki OS provides two communication stacks: uIP and Rime. uIP is an embedded TCP/IP stack and the Rime is a lightweight communication stack which is designed to simplify the implementation of routing protocols in WSNs. The following sections describe these stacks in more detail.

Rime

Rime introduces a set of lightweight communication primitives in a layered structure. Single-hop and multi-hop primitives are supported by the Rime stack.

Higher layer protocols can be easily set on the top of the Rime communication stack and use different kinds of communication primitives. Arbitrary routing protocols use the multi-hop primitives to specify how packets are routed through the network and how the next-hop neighbor is chosen. Figure 2.6 depicts the communication primitives and how they are layered.

Different kinds of communication primitives are as follows:

Anonymous best-effort local area broadcast

Identified best-effort local area broadcast

Best-effort single-hope unicast

Stubborn single-hope unicast

Reliable single-hope unicast

Polite single-hop broadcast

Identified polite single-hop broadcast

Best-effort multi-hop unicast

Hop-by-hop reliable multi-hop unicast

23

Chapter 2. Background

Figure 2.6: Rime communication primitives

The uIP TCP/IP stack

The uIP is an open source and lightweight TCP/IP stack for tiny microcontroller systems and generally smart objects to provide a full IP access to intranet or even the global Internet. The uIP was initially developed by Adam Dunkels of the

“Networked Embedded Systems” group at the Swedish Institute of Computer

Science (SICS); it is written in the C programming language and the following is a list of some of its main features:

Provides the RFC-compliant implementation of IP (version 4 and version 6),

ICMP, UDP and TCP protocols

Very small memory footprint

Very low RAM requirements to implement a full TCP/IP stack

Very small code size

Simple buffer management strategy (e.g. It uses a single memory buffer for both incoming and outgoing packets)

Handles multiple TCP and UDP connections simultaneously

Designed to be used with or without an operating system

Since uIP has implemented a full TCP/IP stack on the resource-constraint devices, the application layer protocols such as HTTP, FTP and SMTP can be implemented by the application programs on top of the uIP stack. A set of functions are called by the application programs to perform network functions and use the services offered by the uIP protocols. Such groups of functions that define the way the application programs interact with the uIP stack are called Application Programming Interfaces

(APIs). The uIP offers two APIs to programmers:

23

Internet to WSN configuration and access using 6LoWPAN 24

raw API: event-based API

Protosocket API: standard BSD socket-like API

The next section describes the raw API programming structure for the TCP and UDP, client/server network communications.

raw API programming

As mentioned above, raw uIP API uses an event driven interface to call the application program in response to certain TCP/IP events. Accordingly, the application is invoked when new data has arrived, when data is acknowledged, when data has to be retransmitted, or a new connection has been set up. Table 2.2 lists the test functions that are used to distinguish between the possible events.

Table 2-2: uIP test functions and the corresponding application events

uip_connected() uip_newdata()

A connection has been successfully established

A packet has arrived

uip_acked()

The acknowledgment packet for the previous data has arrived

uip_rexmit() uip_timedout()

The retransmission timer expires

The connection has been aborted due to too many retransmissions

uip_closed()

The connection has been closed by the remote host

In order to write a TCP or UDP-based applications, a programmer can use the following functions which are provided by uIP raw API:

UDP:

Create a new UDP connection:

struct uip_udp_conn *udp_new (const uip_ipaddr_t *ripaddr, u16_t port, void *appstate)

Bind a UDP connection to a local port:

uip_udp_bind (conn, port)

Send a UDP packet:

uip_udp_packet_send (struct uip_udp_conn *c, const void *data, int len)

25

Chapter 2. Background

&& uip_udp_packet_sendto (struct uip_udp_conn *c, const void *data, int len,

const uip_ipaddr_t *toaddr, uint16_t toport)

TCP:

Open a TCP connection to the specified IP address and port:

struct uip_conn *tcp_connect (uip_ipaddr_t *ripaddr,u16_t port,void *appstate)

Open a local TCP port for listening:

tcp_listen (u16_t port)

Send data on the current connection:

uip_send (const void *data, int len)

25

Chapter 3

3 6LoWPAN Experiment

According to the goal of this thesis, we used Contiki OS and its RFC-Compliant

TCP/IP stack (uIP) to implement 6LoWPAN functionality. In this chapter, we show how to write a UDP-based application in Contiki OS and how to install and configure a deployment-ready 6LoWPAN Border Router called 6LBR on the

Raspberry Pi to connect 6LoWPAN devices to the Internet for data collection and monitoring purposes. As part of our work, we implemented IPv6-over-IPv4 tunnelling on the border router to reach the world wide IPv6-Internet. Figure 3.1 shows the system architecture and its components.

Figure 3.1: The 6LoWPAN application scenario

27

Chapter 3. Methods

3.1 6LoWPAN Border Router (6LBR)

In order to make a connection between the 6LoWPAN motes and the existing IPv6 network we used the 6LoWPAN Border Router (6LBR) which is ready to deploy, running on low-cost and open source hardware platforms such as the Raspberry PI,

Econotog and BeagleBone.

Figure 3.2: The edge router

In this thesis we chose Raspberry PI which is an ultra-low cost, ARM powered, credit card sized Linux-based computer as the edge router. The 802.15.4 interface can be added by using a Tmote Sky mote running the Contiki slip-radio application (Figure

3.2).

The following steps show how to install 6LBR on an existing Raspbian image:

Step 1: install bridge-utils with the following command:

apt-get install bridge-utils

Step 2: Download the 6lbr package on the Raspberry PI (Check for the latest packages first through the 6LBR github page)

wget https://raw.github.com/wiki/cetic/6lbr/releases/cetic-6lbr_1.0-0_armhf.deb

Step 3: Install the package:

dpkg -i cetic-6lbr-1.0-0_armhf.deb

Step 4: Take one of the configurations files from /etc/6lbr and rename it to

6lbr.conf

Step 5: Start the daemon:

/etc/init.d/6lbr start

Internet to WSN configuration and access using 6LoWPAN 28

The following steps show how to flash the Contiki slip-radio application on the USB

Tmote Sky mote:

Step 1: Connect the mote to the Linux/Mac computer

Step 2: Program the mote with the slip-radio application:

cd $CONTIKI_HOME/examples/ipv6/slip-radio

make TARGET=sky slip-radio.upload

3.2 Contiki application

Although the Contiki OS supports both UDP and TCP transport protocols, the

6LoWPAN header compression mechanism only supports UDP packets. Therefore, we implemented UDP as a transport protocol between sensor nodes and the web server. The following are the most important steps that should be considered for writing the Contiki application program:

Set the web server IPv6 global address;

uip_ip6addr(&ipaddr, 0x2001, 0x05c0, 0x1505, 0x6800, 0, 0, 0, 0);

uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr);

uip_ds6_addr_add(&ipaddr, 0, ADDR_AUTOCONF);

Create a new UDP connection with the web server;

server_conn = udp_new(NULL,UIP_HTONS(3500), NULL);

Bind the UDP connection to a local port number;

udp_bind(server_conn, UIP_HTONS(3000));

Set an event timer;

etimer_set(&et, CLOCK_SECOND * 60);

Define an infinite loop which is blocked until a TCP/IP event occurs or the timer expires.

Define a TCP/IP event handler:

 Check the content of received UDP packet which is available from the uIP buffer.

ledno = (int *)uip_appdata ;

Turn on or off the on board LEDs based on the IPv6 data payload.

29

Chapter 3. Methods

if (*ledno == 1) {

leds_on(LEDS_RED);

} else if (*ledno == 2) {

leds_off(LEDS_RED);

}

…..

Define a timer event handler to:

 Retrieve the temperature value using the temperature sensor on the

Tmote Sky board;

char buf[MAX_PAYLOAD_LEN];

sprintf(buf, "%u",get_temp());

Put the temperature value in the IPv6 packet payload;

 Send the UDP packet to the web server

uip_ipaddr_copy(&server_conn->ripaddr, &ipservaddr);

uip_udp_packet_send(server_conn, buf, strlen(buf));

The complete source code of the application is in appendix A.

3.3 Tunnel Broker

As discussed in section 2.3.3, IPv4 is still dominating the Internet and the users have no access to the IPv6 cloud. Therefore, the IETF offered the transition mechanisms to overcome the IPv4 interconnectivity issue. In this scenario we have used the configured-tunnelling method and specifically used Freenet6, IPv6 access service which is provided by gogo6. The following steps will walk through the process of configuring and using the gogoCLIENT on the Raspberry PI:

Step 1: Install gogoClient with the following command:

sudo apt-get update

Step 2: Sign up for gogoNet account and then get the username and password for the Freenet6 IPv6 tunnel.

Step 3: Edit the gogo6 configuration file as follows:

userid= #tunnel user id from step 2 passwd= #tunnel password from step 2 server=montreal.freenet6.net or amsterdam.freenet6.net auth_method=any host_type=router

Internet to WSN configuration and access using 6LoWPAN

if_prefix=eth0

# usually its eth0 or eth1 for ethernet and wlan0 or wlan1 for wireless lan

.

dns_server=2001:4860:4860::8888 tunnel_mode=v6anyv4 log_console=0 log_stderr=1 log_file=1 log_syslog=0 log_filename=/var/log/gogoc/gogoc.log

Step 4: Restart gogoc service with the following commands:

sudo service gogoc restart

Step 5: Run Ifconfig command then you should see "tun" interfaces and

IPv6 address allocated to your PI if you properly configured the gogoc configuration file in step 3.

30

3.4 Web Server

The web server is deployed on Windows Azure Virtual Machine (VM) which is running Windows Server. Based upon the system architecture requirements, the web server basic functions are listed below:

Receive the temperature data from the Tmote Skys via a program and save them in a database.

Provide a web application for IPv4 clients. It should be able to open a IPv6 socket and send out the UDP packet based on user’s request (turning on or off the on board LEDs) .

Create an IPv6 tunnel over existing IPv4 infrastructure which is done by

Freenet6 tunnel broker.

The receiving program is written in VB.NET. Its main features are as follows:

A bound UDP socket receives temperature data from Tmote Sky sensor motes;

The application is linked with a SQL database to store the received temperature values.

The web application (Figure 3.3) has been developed in ASP.NET and hosted by

Windows Azure Virtual Machine (VM). Its main features are as follows:

The application is linked with the database to visually represent the historical records of temperature data;

A web page is offered by the application to control the on board LEDs remotely from the public IPv4 Internet.

31

Chapter 3. Methods

For the complete source code of the web application and the receiving program see

Appendix B.

Figure 3.3: The web application

Internet to WSN configuration and access using 6LoWPAN 32

Chapter 4

4 Analysis of 6LoWPAN experiment and background findings

As we mentioned in section 2.3, smart object networks are faced with many challenges such as scalability, interoperability, diversity of applications, configuration and management. In this section, first, we are going to discuss the non-

IP architecture issues in relation to meeting smart object network challenges. Then, we explain the IPv6-based architecture (6LoWPAN) capabilities with which the challenges are met.

However, although 6LoWPAN benefits from capabilities mentioned above, fragmentation and reassembly is mainly considered as a disadvantage of this solution. The reason is that fragmentation and reassembly increase the energy consumption which is considered as a problem for highly energy constrained devices. Even though the use of IP architecture for smart objects is advocated, it is not advocated that all smart objects should be connected to the public Internet by the means of IP. There are some cases in which smart objects are connected to the

Internet to send data to a database, but this case is considered as an exception, not the norm.

4.1 Gateway issues in Wireless Sensor Networks

When the networking system is not IP-based, multiprotocol translation must be done through gateways. About a decade ago, when IP protocol did not dominate the networks, gateways provided connectivity between private non IP-based networks and IP-based networks , due to its protocol translation ability. Novell’s Internetwork

Packet Exchange protocol (IPX), IBM’s Systems Network Architecture (SNA), and many other networks architecture could connect the public networks through the gateway. From this perspective, gateways seemed to be helpful and reasonable. Why did such non-IP based networks become IP-based networks, eventually? In order to answer this question we investigate two main disadvantages of using gateways in the following section:

4.1.1 Complexity

Networking protocols deploy different mechanisms for routing, Quality of Service

(QoS), security, management and so on. Trying to translate, for example, the semantics of QoS between two different networking protocols is not limited to the setting of new value in a packet header and may sometimes not even be possible.

This fact applies to other mechanisms such as routing, as well. Translating one routing protocol to another routing protocol which uses different routing metrics and architecture introduces many limitations.

Internet to WSN configuration and access using 6LoWPAN 34

In addition, troubleshooting and management will be a hard task if multiple translation gateways are in use. For example, imagine when three smart objects are communicating through three different networking protocols. Troubleshooting and managing such a system is very difficult, since there is a need for six protocol translations.

4.1.2 Lack of flexibility & scalability

As mentioned earlier, scalability and flexibility are the main concerns for smart objects since they are usually expected to be deployed in a large number. Connecting smart objects to the public Internet by the use of protocol translation gateways places limitations on scaling smart object networks up and become networking bottlenecks

[2] since they support a limited number of networking protocols. Moreover, each protocol enhancement imposes changes on the gateways, which can be hard to manage. Furthermore, gateways are not reliable since they represent single points of failure.

4.2 Benefits of 6LoWPAN

In this section we argue the necessity and the importance of the Internet Protocol (IP) for the future of smart objects like wireless sensor nodes. At present, the smart object situation is very similar to what the computer networks looked like around two decades ago: Islands of computer networks communicating with each other over their own different communication protocol such as Vine, SNA and IPX interconnected by complex protocol translation gateways. Eventually, those different architectures were replaced by a single standard protocol called IP which eased the way of communication. Today, the non-IP wireless sensor architectures are using a similar complex protocol-translation model which computer networks did before. So, why not to learn from the past experience and move to the simple IP-based architecture? Yet, there has already been a considerable movement towards IP-based architecture for smart objects because of the gateways problem that we mentioned in the previous section.

In the following sections, we investigate the reasons of using IP for smart objects

(6LoWPAN architecture) to figure out how well it enhances the smart object communications.

4.2.1 Interoperability

Since IP has been widely adopted in today’s networked system, the 6LoWPAN is able to interoperate with a large number of devices, computers and servers.

The widespread use of IP among different platforms and devices caused different operating systems , whether they are open source implementations or not, to support

IP architecture. Generally purposed operating systems like Microsoft and Linux or operating systems designed for microcontrollers such as Contiki and TinyOS have

35

Chapter 4. Results implemented IP. Being supported by different operating systems has rendered IP be ubiquitous.

The IP architecture contains other protocols such as TCP and UDP in addition to the

IP The former is used when data delivery guarantee is needed and the latter is used to provide best-effort service where immediate delivery is more important than reliability. Application layer protocols such as Hyper Text Transfer Protocol (HTTP) and File Transfer Protocol FTP use TCP while, Simple Network Management

Protocol (SNMP) and Domain Name Service (DNS) use UDP. Therefore, the

6LoWPAN can interact with a wide range of applications working with the protocols mentioned above.

4.2.2 6LoWPAN is Flexible

The IP architecture has shown a capability to evolve according to the way applications and protocols have developed during the recent decades. From the start, the IP was designed in a way that allows the application layer protocols to experience slight changes independently of the underlying network layers and protocols; the versatility and ability to evolve are obtained due to the end-to-end principles provided by the IP architecture.

The end-to-end principle provided by IP governs how the application layer functionality is carried out. The IP layer takes the responsibility of delivering packets to the destination across the network. This is the IP packet header (created in the IP layer) that holds the address of destination and the IP network (the intermediate devices on the way) can forward the packet until it is delivered to the destination.

The path taken by the packet is computed by the intermediate devices according to their routing tables.

The intermediated devices which work in the IP layer have no idea if they are transmitting temperature received from a temperature sensor, a piece of sound from a song, a piece of video from a movie or a control command. They can just realize that they have been granted some streams of bits from one end-point (source) of a network and have the responsibility to choose the best path towards the destination.

The end-to-end principle is one of the main reasons that the 6LoWPAN is capable of working with a wide variety of different applications.

4.2.3 6LoWPAN is scalable

6LoWPAN supports scalability as each node in the network is able to receive a globally unique IPv6 address.

IP has proven to be scalable over the public Internet. No other communication architecture could provide such a large scale like IP. As the Internet of Things vision is to connect a large number of smart objects to the Internet, scalability is one of the main concerns.

Internet to WSN configuration and access using 6LoWPAN

4.2.4 6LoWPAN is standardized

36

Since the core of the public Internet, the IP layer and its surrounding protocols such as TCP, UDP and other protocols receive updates and obtain licenses from the IETF to be recognized as a standard, the IP architecture will keep working well in the future.

The global standardization of IP leads the majority of the vendors and the IT companies to provide the products and networking equipment whose hardware and software work is according to the IETF standards. Consequently, IP architecture becomes prevalent and IP-based networking devices will dominate the IP networking society. It encourages IP network access and IP networking equipment to continue to be , as long as the Internet exists.

4.2.5 Ease of configuration and management

Because of the wide adoption and the large address space of IP, it provides many mechanisms and protocols used for the network management and configuration.

When it comes to the smart objects with a large number in a network, the necessity of these mechanisms becomes more obvious. For example, in our 6LoWPAN scenario, we are able to ping each device from everywhere to check whether they are connected. IP also provides several routing protocols such as RIP, OSPF to automatically determine an optimized path towards the destination. Moreover,

SNMP protocol is used by a network administrator to monitor the network management, configuration and performance. There are plenty of tools which enable an administrator to examine networks working based on SNMP protocol. Moreover,

IPv6 offers the “plug-and-play” mechanism that helps the 6LoWPAN devices to derive their own address independently and without any manual configuration or intervention from an administrator. The plug-and-play capability enables IPv6 nodes to move between more than one LoWPAN at the same time.

4.2.6 6LoWPAN is secure

While writing this thesis, an End-to-End (E2E) secure communication between IP enabled sensor networks and the traditional Internet was provided. This is the first compressed lightweight design, implementation, and evaluation of 6LoWPAN extension for IPsec. The extension supports both IPsec’s Authentication Header (AH) and Encapsulation Security Payload (ESP). Thus, communication endpoints are able to authenticate, encrypt and check the integrity of messages using standardized and established IPv6 mechanisms.

4.2.7 6LoWPAN is lightweight

IP used to be heavy, large and power consuming for low-power and memoryconstrained microcontrollers of smart object devices. The available memory of these microcontrollers is usually a few kilobytes. Additionally, their power resources are

37

Chapter 4. Results

Figure 4.1: The memory footprint of five embedded TCP/IP stacks [2]: the Arch Rock stack

(Arv6), Sensinode, NanoStack (NSv6), uIP, uIPv6, lwIP. severely limited. Therefore, the memory efficient implementation of the IP stack has been offered to deal with the problem.

As we discussed in 2.7.3, uIP is an open-source and memory efficient implementation of the TCP/IP which embraces all the key mechanisms provided by the TCP/IP stack that enable the smart objects to be connected to both the private networks and the public Internet. Recently, uIP has been developed to uIPv6 which supports IPv6. The uIPv6 is considered as the first small implementation of IPv6 for the smart objects. Figure 4.1 shows the memory footprint of five embedded TCP/IP stacks.

4.2.8 Major differences between 6LoWPAN and the alternatives

During this thesis we talked indirectly about the differences between the 6LoWPAN and its alternative solutions. Here, the major differences between the two architectures are briefly depicted.

Table 4-1 Non-IP Architectures versus 6LoWPAN

Non-IP Architectures 6LoWPAN

Proprietary alternatives Standardized architecture by IETF

Protocol-Translation Gateway:

complex to design, manage and deploy

Edge Router:

End-to-end communication between devices

(Scalable, stable, efficient)

Internet to WSN configuration and access using 6LoWPAN

Non-standard device-related application programming

38

Used for a wide-range of applications, on a wide range of devices, and over a wide range of underlying network technologies

Objects are identified by their device IDs,

MAC addresses or Vendors ID

Smart objects have a globally unique identification address (IPv6) over the

Internet

Indirect access through gateway

Real end-to-end connectivity (through the edge router)

Direct access to the 6LoWPAN nodes

- Scalable over the public Internet

5 Conclusions

In order to fulfil the Internet of Things goals, smart object challenges should be met.

Challenges mainly include interoperability, scalability, diversity of applications, standardization, configuration and management. Therefore, deploying a network architecture that can meet these challenges simultaneously is of interest. In this thesis, we configured an IPv6-based Wireless Sensor Network using a Contiki embedded operating system to implement 6LoWPAN functionality for constrained devices. This standard WSN is able to send the measured environment temperature to a web server and control the status of a light through the Internet. As we discussed in this thesis, this WSN benefits considerably from IPv6 advantages. It supports scalability as each node in the network is able to receive a globally unique

IPv6 address. Moreover, the 6LoWPAN network is standardized by IETF which leads the network to support all the IP-based 802.15.4 devices from different vendors to provide flexibility. Furthermore, using 6LoWPAN eliminates the complex protocol translation gateways. Instead, 6LoWPAN nodes can be seamlessly connected to the

Internet through the edge router and provides a real end-to-end communication. All in all, this WSN uses the 6LoWPAN to be compatible with the Internet of Things goals.

Appendix A

The Contiki application source code:

#include "contiki.h"

#include "contiki-lib.h"

#include "contiki-net.h"

#include "dev/sht11-sensor.h"

#include <string.h>

#include "dev/slip.h"

#define DEBUG DEBUG_PRINT

#include "net/uip-debug.h"

#include "dev/leds.h"

#define UIP_IP_BUF ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])

#define MAX_PAYLOAD_LEN 120 static struct uip_udp_conn *server_conn;

PROCESS(udp_server_process, "UDP server process");

AUTOSTART_PROCESSES(&udp_server_process);

/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/ static int get_temp(void)

{

return ((sht11_sensor.value(SHT11_SENSOR_TEMP) / 10) - 396) / 10;

}

/*---------------------------------------------------------------------------*/ static void tcpip_handler(void)

{

static int *ledno;

if(uip_newdata()) {

ledno = (int *)uip_appdata ;

PRINTF("Server received: %d", ledno);

PRINTF("\n");

if (*ledno == 1) {

leds_on(LEDS_RED);

}

41

Appendix B

else if (*ledno == 2) {

leds_off(LEDS_RED);

}

else if (*ledno == 3) {

leds_on(LEDS_BLUE);

}

else if (*ledno == 4) {

leds_off(LEDS_BLUE);

}

else if (*ledno == 5) {

leds_on(LEDS_GREEN);

}

else if (*ledno == 6) {

leds_off(LEDS_GREEN);

}

else if (*ledno == 7) {

leds_off(LEDS_GREEN);

}

}

}

/*---------------------------------------------------------------------------*/ static void periodicmsg(void)

{

uip_ipaddr_t ipservaddr;

uip_ip6addr(&ipservaddr, 0x2001, 0x05c0, 0x1400, 0x000b, 0, 0, 0, 0x2611);

char buf[MAX_PAYLOAD_LEN];

sprintf(buf, "%u",get_temp());

uip_ipaddr_copy(&server_conn->ripaddr, &ipservaddr);

uip_udp_packet_send(server_conn, buf, strlen(buf));

/* Restore server connection to allow data from any node */

memset(&server_conn->ripaddr, 0, sizeof(server_conn->ripaddr));

}

/*---------------------------------------------------------------------------*/ static void print_local_addresses(void)

{

int i;

uint8_t state;

PRINTF("Server IPv6 addresses: ");

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

state = uip_ds6_if.addr_list[i].state;

if(uip_ds6_if.addr_list[i].isused &&

(state == ADDR_TENTATIVE || state == ADDR_PREFERRED)) {

PRINT6ADDR(&uip_ds6_if.addr_list[i].ipaddr);

41

Internet to WSN configuration and access using 6LoWPAN

PRINTF("\n");

}

}

}

/*---------------------------------------------------------------------------*/

PROCESS_THREAD(udp_server_process, ev, data)

{

static struct etimer et,etled;

#if UIP_CONF_ROUTER

uip_ipaddr_t ipaddr;

#endif /* UIP_CONF_ROUTER */

PROCESS_BEGIN();

PRINTF("UDP server started\n");

SENSORS_ACTIVATE(sht11_sensor);

#if UIP_CONF_ROUTER

uip_ip6addr(&ipaddr, 0x2001, 0x05c0, 0x1505, 0x6800, 0, 0, 0, 0);

uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr);

uip_ds6_addr_add(&ipaddr, 0, ADDR_AUTOCONF);

#endif /* UIP_CONF_ROUTER */

print_local_addresses();

server_conn = udp_new(NULL,UIP_HTONS(3500), NULL);

udp_bind(server_conn, UIP_HTONS(3000));

etimer_set(&et, CLOCK_SECOND * 60);

while(1) {

PROCESS_YIELD();

if(ev == tcpip_event) {

tcpip_handler();

}

}

if(etimer_expired(&et)) {

periodicmsg();

}

}

PROCESS_END();

42

Appendix B

The web application source code:

Imports Microsoft.VisualBasic

Imports System.Drawing

Imports System.Drawing.Imaging

Imports System.Web

Imports System

Imports System.Net

Imports System.Net.Sockets

Imports System.Text

Imports System.Data.SqlClient

Imports System.Data.SqlClient.SqlDataReader

Public Class WebForm1

Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles

Me.Load

Dim temp As Decimal

Dim db1 As New SqlConnection

Dim rd As SqlDataReader

Dim rd2 As SqlDataReader

Dim rd3 As SqlDataReader

Dim rd4 As SqlDataReader

Dim status As Integer = 0

Dim txt As String = ""

db1.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename='" &

"C:\inetpub\wwwroot\App_Data\Database.mdf'" & ";Integrated Security=True;User

Instance=True"

db1.Open()

Dim cmd1 As New SqlCommand

cmd1.Connection = db1

cmd1.CommandText = " DELETE FROM Temp#1 " & _

" INSERT INTO Temp#1 (Result) VALUES ((SELECT Temp FROM temp

WHERE No = IDENT_CURRENT('temp'))) "

cmd1.ExecuteNonQuery()

Dim cmd2 As New SqlCommand

cmd2.Connection = db1

cmd2.CommandText = " SELECT Result FROM Temp#1 "

cmd2.ExecuteNonQuery()

rd = cmd2.ExecuteReader

If rd.Read Then

txt = rd.GetString(0)

End If

temp = Decimal.Parse(txt)

Internet to WSN configuration and access using 6LoWPAN 44

Image1.ImageUrl =

"http://www.jlion.com:80//tools/Thermometer.aspx?MIN=0&MAX=50&VT=2&T=Thermo meter Chart&IV=" & temp & "&M=1&SC=0&CS=6&CI=en-US&TH=1"

rd.Close()

Dim cmd3 As New SqlCommand

' RED LED status recognition

cmd3.Connection = db1

cmd3.CommandText = " SELECT status FROM Act WHERE ID = 1 "

cmd3.ExecuteNonQuery()

rd2 = cmd3.ExecuteReader

If rd2.Read Then

txt = rd2.GetString(0)

End If

status = Integer.Parse(txt)

If status = 1 Then

ImageButton1.Visible = True

Else

ImageButton2.Visible = True

End If

rd2.Close()

Dim cmd4 As New SqlCommand

' BLUE LED status recognition

cmd4.Connection = db1

cmd4.CommandText = " SELECT status FROM Act WHERE ID = 2 "

cmd4.ExecuteNonQuery()

rd3 = cmd4.ExecuteReader

If rd3.Read Then

txt = rd3.GetString(0)

End If

status = Integer.Parse(txt)

If status = 1 Then

ImageButton4.Visible = True

Else

ImageButton3.Visible = True

End If

rd3.Close()

Dim cmd5 As New SqlCommand

' GREEN LED status recognition

cmd5.Connection = db1

cmd5.CommandText = " SELECT status FROM Act WHERE ID = 3 "

cmd5.ExecuteNonQuery()

rd4 = cmd5.ExecuteReader

If rd4.Read Then

txt = rd4.GetString(0)

End If

status = Integer.Parse(txt)

If status = 1 Then

ImageButton6.Visible = True

Else

ImageButton5.Visible = True

45

Appendix B

End If

rd4.Close()

db1.Close()

End Sub

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles

Button1.Click

Panel3.Visible = True

Image1.Visible = True

Panel4.Visible = False

End Sub

Protected Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles

Button3.Click

Panel3.Visible = False

Image1.Visible = False

Panel4.Visible = True

End Sub

Protected Sub ImageButton1_Click(ByVal sender As Object, ByVal e As

System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click

Dim db2 As New SqlConnection

db2.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename='" &

"C:\inetpub\wwwroot\App_Data\Database.mdf'" & ";Integrated Security=True;User

Instance=True"

db2.Open()

Dim cmd1 As New SqlCommand

Dim s As New Socket(AddressFamily.InterNetworkV6, SocketType.Dgram,

ProtocolType.Udp)

Dim txt As String = ""

Dim addrs As IPAddress = IPAddress.IPv6Any

Dim addrd As IPAddress = IPAddress.Parse("aaaa:0:0:0:212:7400:13cb:1fa6")

Dim ledno As Integer = 2

Dim sendBytes As [Byte]() = BitConverter.GetBytes(ledno)

Dim recvBytes(255) As Byte

Dim eps As New IPEndPoint(addrs, 3500)

Dim epd As New IPEndPoint(addrd, 3000)

Try

s.Bind(eps)

s.SendTo(sendBytes, epd)

s.Receive(recvBytes)

txt = Encoding.ASCII.GetString(recvBytes)

If txt <> "" Then

cmd1.Connection = db2

cmd1.CommandText = " UPDATE Act SET status = '0' WHERE ID = 1 "

cmd1.ExecuteNonQuery()

ImageButton1.Visible = False

45

Internet to WSN configuration and access using 6LoWPAN

ImageButton2.Visible = True

End If

s.Close()

Catch

s.Close()

Label1.Visible = True

End Try

db2.Close()

End Sub

Protected Sub ImageButton2_Click(ByVal sender As Object, ByVal e As

System.Web.UI.ImageClickEventArgs) Handles ImageButton2.Click

Dim db2 As New SqlConnection

db2.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename='" &

"C:\inetpub\wwwroot\App_Data\Database.mdf'" & ";Integrated Security=True;User

Instance=True"

db2.Open()

Dim cmd1 As New SqlCommand

Dim s As New Socket(AddressFamily.InterNetworkV6, SocketType.Dgram,

ProtocolType.Udp)

Dim txt As String = ""

Dim addrs As IPAddress = IPAddress.IPv6Any

Dim addrd As IPAddress = IPAddress.Parse("aaaa:0:0:0:212:7400:13cb:1fa6")

Dim ledno As Integer = 1

Dim sendBytes As [Byte]() = BitConverter.GetBytes(ledno)

Dim recvBytes(255) As Byte

Dim eps As New IPEndPoint(addrs, 3500)

Dim epd As New IPEndPoint(addrd, 3000)

Try

s.Bind(eps)

s.SendTo(sendBytes, epd)

s.Receive(recvBytes)

txt = Encoding.ASCII.GetString(recvBytes)

If txt <> "" Then

cmd1.Connection = db2

cmd1.CommandText = " UPDATE Act SET status = '1' WHERE ID = 1 "

cmd1.ExecuteNonQuery()

ImageButton1.Visible = True

ImageButton2.Visible = False

End If

s.Close()

Catch

s.Close()

Label1.Visible = True

End Try

db2.Close()

End Sub

46

47

Appendix B

Protected Sub ImageButton4_Click(ByVal sender As Object, ByVal e As

System.Web.UI.ImageClickEventArgs) Handles ImageButton4.Click

Dim db2 As New SqlConnection

db2.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename='" &

"C:\inetpub\wwwroot\App_Data\Database.mdf'" & ";Integrated Security=True;User

Instance=True"

db2.Open()

Dim cmd1 As New SqlCommand

Dim s As New Socket(AddressFamily.InterNetworkV6, SocketType.Dgram,

ProtocolType.Udp)

Dim txt As String = ""

Dim addrs As IPAddress = IPAddress.IPv6Any

Dim addrd As IPAddress = IPAddress.Parse("aaaa:0:0:0:212:7400:13cb:1fa6")

Dim ledno As Integer = 4

Dim sendBytes As [Byte]() = BitConverter.GetBytes(ledno)

Dim recvBytes(255) As Byte

Dim eps As New IPEndPoint(addrs, 3500)

Dim epd As New IPEndPoint(addrd, 3000)

Try

s.Bind(eps)

s.SendTo(sendBytes, epd)

s.Receive(recvBytes)

txt = Encoding.ASCII.GetString(recvBytes)

If txt <> "" Then

cmd1.Connection = db2

cmd1.CommandText = " UPDATE Act SET status = '0' WHERE ID = 2 "

cmd1.ExecuteNonQuery()

ImageButton3.Visible = True

ImageButton4.Visible = False

End If

s.Close()

Catch

s.Close()

Label1.Visible = True

End Try

db2.Close()

End Sub

Protected Sub ImageButton3_Click(ByVal sender As Object, ByVal e As

System.Web.UI.ImageClickEventArgs) Handles ImageButton3.Click

Dim db2 As New SqlConnection

db2.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename='" &

"C:\inetpub\wwwroot\App_Data\Database.mdf'" & ";Integrated Security=True;User

Instance=True"

db2.Open()

Dim cmd1 As New SqlCommand

Dim s As New Socket(AddressFamily.InterNetworkV6, SocketType.Dgram,

ProtocolType.Udp)

Dim txt As String = ""

Dim addrs As IPAddress = IPAddress.IPv6Any

47

Internet to WSN configuration and access using 6LoWPAN

Dim addrd As IPAddress = IPAddress.Parse("aaaa:0:0:0:212:7400:13cb:1fa6")

Dim ledno As Integer = 3

Dim sendBytes As [Byte]() = BitConverter.GetBytes(ledno)

Dim recvBytes(255) As Byte

Dim eps As New IPEndPoint(addrs, 3500)

Dim epd As New IPEndPoint(addrd, 3000)

Try

s.Bind(eps)

s.SendTo(sendBytes, epd)

s.Receive(recvBytes)

txt = Encoding.ASCII.GetString(recvBytes)

If txt <> "" Then

cmd1.Connection = db2

cmd1.CommandText = " UPDATE Act SET status = '1' WHERE ID = 2 "

cmd1.ExecuteNonQuery()

ImageButton4.Visible = True

ImageButton3.Visible = False

End If

s.Close()

Catch

s.Close()

Label1.Visible = True

End Try

db2.Close()

End Sub

Protected Sub ImageButton6_Click(ByVal sender As Object, ByVal e As

System.Web.UI.ImageClickEventArgs) Handles ImageButton6.Click

Dim db2 As New SqlConnection

db2.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename='" &

"C:\inetpub\wwwroot\App_Data\Database.mdf'" & ";Integrated Security=True;User

Instance=True"

db2.Open()

Dim cmd1 As New SqlCommand

Dim s As New Socket(AddressFamily.InterNetworkV6, SocketType.Dgram,

ProtocolType.Udp)

Dim txt As String = ""

Dim addrs As IPAddress = IPAddress.IPv6Any

Dim addrd As IPAddress = IPAddress.Parse("aaaa:0:0:0:212:7400:13cb:1fa6")

Dim ledno As Integer = 6

Dim sendBytes As [Byte]() = BitConverter.GetBytes(ledno)

Dim recvBytes(255) As Byte

Dim eps As New IPEndPoint(addrs, 3500)

Dim epd As New IPEndPoint(addrd, 3000)

Try

s.Bind(eps)

s.SendTo(sendBytes, epd)

s.Receive(recvBytes)

txt = Encoding.ASCII.GetString(recvBytes)

48

49

Appendix B

If txt <> "" Then

cmd1.Connection = db2

cmd1.CommandText = " UPDATE Act SET status = '0' WHERE ID = 3 "

cmd1.ExecuteNonQuery()

ImageButton5.Visible = True

ImageButton6.Visible = False

End If

s.Close()

Catch

s.Close()

Label1.Visible = True

End Try

db2.Close()

End Sub

Protected Sub ImageButton5_Click(ByVal sender As Object, ByVal e As

System.Web.UI.ImageClickEventArgs) Handles ImageButton5.Click

Dim db2 As New SqlConnection

db2.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename='" &

"C:\inetpub\wwwroot\App_Data\Database.mdf'" & ";Integrated Security=True;User

Instance=True"

db2.Open()

Dim cmd1 As New SqlCommand

Dim s As New Socket(AddressFamily.InterNetworkV6, SocketType.Dgram,

ProtocolType.Udp)

Dim txt As String = ""

Dim addrs As IPAddress = IPAddress.IPv6Any

Dim addrd As IPAddress = IPAddress.Parse("aaaa:0:0:0:212:7400:13cb:1fa6")

Dim ledno As Integer = 5

Dim sendBytes As [Byte]() = BitConverter.GetBytes(ledno)

Dim recvBytes(255) As Byte

Dim eps As New IPEndPoint(addrs, 3500)

Dim epd As New IPEndPoint(addrd, 3000)

Try

s.Bind(eps)

s.SendTo(sendBytes, epd)

s.Receive(recvBytes)

txt = Encoding.ASCII.GetString(recvBytes)

If txt <> "" Then

cmd1.Connection = db2

cmd1.CommandText = " UPDATE Act SET status = '1' WHERE ID = 3 "

cmd1.ExecuteNonQuery()

ImageButton6.Visible = True

ImageButton5.Visible = False

End If

s.Close()

Catch

s.Close()

Label1.Visible = True

End Try

db2.Close()

End Sub

49

Internet to WSN configuration and access using 6LoWPAN 50

Protected Sub Button4_Click(ByVal sender As Object, ByVal e As EventArgs) Handles

Button4.Click

Dim db2 As New SqlConnection

db2.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename='" &

"C:\inetpub\wwwroot\App_Data\Database.mdf'" & ";Integrated Security=True;User

Instance=True"

db2.Open()

Dim cmd1 As New SqlCommand

cmd1.Connection = db2

cmd1.CommandText = " UPDATE Act SET status = '0' "

cmd1.ExecuteNonQuery()

db2.Close()

ImageButton2.Visible = True

ImageButton1.Visible = False

ImageButton3.Visible = True

ImageButton4.Visible = False

ImageButton5.Visible = True

ImageButton6.Visible = False

End Sub

End Class

The receiving program source code:

Imports System

Imports System.Threading

Imports System.Net

Imports System.Net.Sockets

Imports System.Text

Imports System.Windows.Forms

Imports System.Data.SqlClient

Public Class Form1

Dim s As New Socket(AddressFamily.InterNetworkV6, SocketType.Dgram,

ProtocolType.Udp)

Dim db1 As New SqlConnection

Private Sub hosting()

Dim port As Integer

Dim txt As String

port = TextBox1.Text

Dim addrs As IPAddress = IPAddress.Parse("2001:5c0:1400:b::2611")

Dim eps As New IPEndPoint(addrs, port)

Dim recvBytes(255) As Byte

Source=.\SQLEXPRESS;AttachDbFilename=C:\inetpub\wwwroot\App_Data\Database.md

f;Integrated Security=False;Connect Timeout=30"

db1.ConnectionString = "Data Source=SIXBEE\SQLEXPRESS;Integrated

Security=True;Initial Catalog=6bee;Connect Timeout=30"

db1.Open()

Try

51

Appendix B

Dim cmd1 As New SqlCommand

s.Bind(eps)

Do

ListBox1.Items.Add("[SERVER] Waiting for message on Port '" & port & "'...")

s.Receive(recvBytes)

ListBox1.Items.Add("[SERVER] Receive a message.")

txt = Encoding.ASCII.GetString(recvBytes)

ListBox1.Items.Add("[Client] '" & txt)

cmd1.Connection = db1

cmd1.CommandText = "INSERT INTO temp (Temp) VALUES ('" & txt & "')"

cmd1.ExecuteNonQuery()

ListBox1.Items.Add("[SERVER] Database update .")

Loop

s.Close()

Catch ex As Exception

s.Close()

ListBox1.Items.Add("[SERVER] Connectivity Problem!")

Button2.Enabled = True

Button1.Enabled = True

End Try

End Sub

Public Sub multi_servstart()

Dim thread As System.Threading.Thread

thread = New System.Threading.Thread(AddressOf hosting)

thread.Start()

End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)

Handles MyBase.Load

Control.CheckForIllegalCrossThreadCalls = False

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

Handles Button1.Click

If Not (IsNumeric(TextBox1.Text)) Or Not ((TextBox1.Text >= 1) And (TextBox1.Text <=

65535)) Then

MsgBox("Please Enter a valid port number!", MsgBoxStyle.Critical)

Else

Button2.Enabled = True

Button1.Enabled = False

multi_servstart()

End If

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

Handles Button2.Click

s.Close()

db1.Close()

ListBox1.Items.Add("[SERVER] Disconnect.")

Me.Close()

End Sub

End Class

51

Bibliography

[1] S. Thomson, T. Narten and T. Jinmei (2007)

IPv6 Stateless Address Autoconfiguration, RFC 4862, Internet Engineering Task

Force.

[2] Jean-Philippe Vasseur, Adam Dunkels (2010)

Interconnecting Smart Objects with IP The Next Internet. 29 .

[3] IEEE Std 802.15.4 (2011) (Revision of IEEE Std 802.15.4-2006).

IEEE Standard for Information Technology- Telecommunications and Information

Exchange Between Systems- Local and Metropolitan Area Networks- Specific

Requirements Part 15.4: Wireless Medium Access Control (MAC) and Physical Layer

(PHY) Specifications for Low-Rate Wireless Personal Area Networks (WPANs).

[4] ZigBee Alliance

http://www.zigbee.org/

[5] V. Cerf and R. Kahn (1974)

A protocol for packet network intercommunication. IEEE Transactions on

Communications, 22(5),637-648.

[5] J. Postel. Internet Protocol (1981)

RFC 0791, Internet Engineering Task Force.

[6] S. Deering and R. Hinden (1998)

Internet Protocol, Version 6 (IPv6) Specification, RFC 2460, Internet Engineering Task

Force.

[7] R. Hinden and S. Deering (2006)

IP Version 6 Addressing Architecture, RFC 4291, Internet Engineering Task Force.

[8] S. Thomson, T. Narten, and T. Jinmei (2007)

IPv6 Stateless Address Autoconfiguration, RFC 4862, Internet Engineering Task

Force.

[9] N. Kushalnagar, G. Montenegro, and C. Schumacher (2007)

IPv6 over Low-Power Wireless Personal Area Networks (6LoWPANs): Overview,

Assumptions, Problem Statement, and Goals, RFC 4919, Internet Engineering Task

Force.

[10] G. Montenegro, N. Kushalnagar, J. Hui, and D. Culler. (2007)

Transmission Of IPv6 Packets over IEEE 802.15.4 Networks, RFC 4944, Internet

Engineering Task Force.

53

Appendix B

[11] J. Hui and P. Thubert (2011)

Compression Format for IPv6 Datagrams over IEEE 802.15.4-Based Networks, RFC

6282, Internet Engineering Task Force.

[12] Adam Dunkels, Oliver Schmidt, Thiemo Voigt, and Muneeb Ali (2006)

Protothreads: Simplifying event-driven programming of memory constrained embedded systems. Proceedings of the Fourth ACM Conference on Embedded

Networked Sensor Systems.

[13] K. Egevang and P. Francis (1994)

The IP Network Address Translator (NAT), RFC 1631, Internet Engineering Task

Force.

[14] D. Johnson, C. Perkins and J. Arkko (2004)

Mobility Support in IPv6, RFC 3775, Internet Engineering Task Force.

[15] Adam Dunkels (2003)

Full TCP/IP for 8-Bit Architectures, Proceedings of The First International

Conference on Mobile Systems, Applications, and Services (MOBISYS ’ 03).

[16] Durvy M, Abeill é J, Wetterwald P. et al (2008)

Making Sensor Networks IPv6 Ready. In: Proceedings of the Sixth ACM Conference on Networked Embedded Sensor Systems (ACM SenSys 2008).

[17] Z. Shelby, S. Chakrabarti and E. Nordmark (2012)

Neighbor Discovery Optimization for IPv6 over Low-Power Wireless Personal Area

Networks(6LoWPANs), RFC 6775, Internet Engineering Task Force

53

Internet to WSN configuration and access using 6LoWPAN 54











































Was this manual useful for you? yes no
Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF

advertisement