On the Optimization of Multiple Applications for Sensor Networks
Full text
On the Optimization of Multiple Applications for Sensor Networks Submitted in partial fulfilment of the requirements for the degree of Doctor of Philosophy in Electrical and Computer Engineering Vikram Gupta Bachelor of Technology, Electronics and Communications Engineering, Visvesvaraya National Institute of Technology, Nagpur, India Master of Science, Electrical and Computer Engineering, Carnegie Mellon University Carnegie Mellon University, Pittsburgh, USA Faculdade de Engenharia da Universidade do Porto, Portugal Fall 2014
FACULDADE DE ENGENHARIA DA UNIVERSIDADE DO PORTO On the Optimization of Multiple Applications for Sensor Networks Vikram Gupta Doctoral Program in Electrical and Computer Engineering (PDEEC) Supervisors: Eduardo Tovar & Ragunathan Rajkumar October 15, 2014
c Vikram Gupta, 2014
On the Optimization of Multiple Applications for Sensor Networks Vikram Gupta Doctoral Program in Electrical and Computer Engineering (PDEEC) Approved by: President: Dr. José Alfredo Ribeiro da Silva Matos Refree: Dr. Peter Steenkiste Refree: Dr. Anthony Rowe Supervisor: Dr. Ragunathan (Raj) Rajkumar Supervisor: Dr. Eduardo Tovar October 15, 2014
For the love of science
perfection and expects the same from his students, which is very inspiring. I will always be grateful to both my advisors for supporting me and giving me an opportunity to work on interesting problems with great people. I would also like to thank Prof. Peter Steenkiste, Prof. Anthony Rowe and Prof. Jos´ e Silva Matos for agreeing to be on my thesis committee. Prof. Peter was one of my earliest contacts in Pittsburgh when I started at CMU. I had the opportunity to spend some time with him while sightseeing in Porto, before I formally started the program. Those interactions with him helped me understand what a PhD and the life in the US means, and I got a first-hand overview of research at CMU. Prof. Peter has always been very helpful and encouraging during several interactions I had with him. Prof. Anthony has been a senior mentor to me even when he was a graduate student during the early part of my doctoral studies. My first research project was under his co-supervision and it was a great initiation to various aspects of research including experimentation, design of hardware and technical writing. Since then, Anthony has been a great mentor and a very helpful critic. I am particularly thankful to Prof. Matos for agreeing to be on the committee. He is always approachable, kind and helpful to students as an in-charge of the Electrical Engineering PhD program at FEUP. I also extend my sincere thanks to several colleagues at Carnegie Mellon: Karthik Lakshmanan, Arvind Kandhalu, Junsung Kim, Gaurav Bhatia and Reza Azimi. Karthik was also a mentor as a senior student and he was always ready to help and guide in many research/technical challenges. The fact that a course project with Junsung and Aditi Pandya as my team-members and Karthik and Arvind as course-teaching assistants became a stepping-stone for my thesis topic is an acknowledgement of their contribution, and I thank them for this. Being with such colleagues is a learning experience by itself, and informal discussions with them during lunch or coffee breaks were stress relievers, motivators and also stress enhancers (near deadlines) at the same time. My fellow researchers and students at the CISTER research lab are a great set of people and they have been supportive in many ways. I would like to thank Nuno Pereira for his help, guidance and his faith in me, especially for including me in the writing of a project proposal. In addition, I would also like to thank Prof. Luis Miguel Pinho for his valuable inputs in the sMapReduce project. There is a long list of people who I would like to thank as well. Vincent Nelis, Geoffrey Nelissen, Patrick Yomsi, Gurulingesh Raravi, Ali Awan, Dakshina Dasari, Jos´ e Marinho, Jo˜ ao Loureiro, Ricardo Garibay, Shashank Gaur and Borislav Nikolic provided several opportunities to brainstorm on
academic and non-academic issues. In addition to creating a great working environment in the lab, our social interactions helped create a nice work-life balance. Innumerable evening tea sessions, several dinners and board-games nights has made my time in Porto very memorable. I am also thankful to Shashank Gaur for his help in the Network-Harmonized Scheduling project and Maryam Vahabi for giving me an opportunity to work on a really interesting problem. I would also like to thank my close friends from undergraduate years who have been very supportive and encouraging. Keshav Seshadri is a very close friend and we were flatmates for the duration of my stay in Pittsburgh. He has always been a very generous host to me whenever I visited Pittsburgh for short durations. It was Keshav who first led me to apply for the CMU-Portugal program. His organized style of working and attention to detail has always motivated me. Keshav, Kandarp Shah, Soumya Jain and Anand Srinivasan have been close friends for more than ten years now, and meeting with them instills energy whenever I feel low and need a little push. They have always been ready to discuss my research problems, and provided a great third-person’s point of view. My family’s faith and confidence in me was a guiding light throughout the PhD. My family has always supported me and given me freedom to pursue my dreams, except only the frequent “When will you graduate?” questions. I am thankful to my mother for always inspiring me to excel in academics. My father always encouraged my wild and crazy ideas in my childhood and taught me to remain curious. He is not with us anymore, but I hope that I have made him proud. I am indebted to my younger brother, Manish, who actually played the role of an elder brother by letting me pursue my graduate studies while he took care of the family back home. My elder sisters, Parveen, Payal and Hittu have always encouraged me to achieve the best. I sincerely hope that I continue to meet their expectations. Finally, I do not have many words to express my love and gratitude for my wife, Kritika who supported me throughout and made my student life so comfortable, even if it meant cooking snacks for me in the middle of the night or staying up until very late to align her schedule with mine. Last but not the least, I would like to acknowledge Funda¸c˜ao para a Ciˆencia e a Tecnologia (FCT) for providing the funding through the CMU-Portugal program and the PATTERN project. The staff at CMU and ICTI has helped me out several times in working out various administrative details. In addition to the administrative support, Prof. Jos´ e Moura, Prof. Jo˜ ao Claro and Prof. Aur´ elio
Campilho have always been extremely helpful in answering my doubts and pointing me in the right direction for fulfilling both the CMU and FEUP requirements.
Contents List of Tables vii List of Figures ix 1 Introduction 1 1.1 Background on Wireless Sensor Networks . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.2 MotivationandChallenges ................................... 5 1.2.1 ProgrammingSupport.................................. 6 1.2.2 Inter-application Redundancy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.2.3 Conforming to Resource Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.2.4 NetworkCoordination.................................. 7 1.3 ThesisStatement ......................................... 8 1.4 Proposedapproach........................................ 9 1.4.1 ProgrammingFramework................................ 9 1.4.2 RedundancyElimination ................................ 9 1.4.3 Hierarchical Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 1.4.4 Network-Harmonized Scheduling . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 1.5 ScopeoftheDissertation..................................... 12
Contents 1.6 Organizationofthethesis .................................... 13 2 Background 15 2.1 Platforms.............................................. 16 2.2 Sensor Network Software Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 2.2.1 OperatingSystems.................................... 19 2.2.2 ProgrammingSupport.................................. 22 2.3 Communication and Networking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 2.3.1 Medium-Access Layer Technologies . . . . . . . . . . . . . . . . . . . . . . . . . . 25 2.3.2 Routing and Data Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 3 Related Work 33 3.1 Programming Sensor Networks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 3.1.1 Over-the-Air Programming Frameworks . . . . . . . . . . . . . . . . . . . . . . . 34 3.1.2 MiddlewareApproaches ................................ 37 3.1.3 Abstractions for Macro-programming . . . . . . . . . . . . . . . . . . . . . . . . . 39 3.2 Redundancy Elimination across Applications . . . . . . . . . . . . . . . . . . . . . . . . . 40 3.3 NetworkCoordination...................................... 42 4 The Nano-CF Programming Framework 45 4.1 Motivation............................................. 46 4.2 SystemDesign........................................... 47 4.2.1 Nano-RK: a Resource-centric RTOS for Sensor Nodes . . . . . . . . . . . . . . . . 49 4.2.2 RoutingandLinkLayer................................. 50 4.3 Nano-CL.............................................. 50 4.3.1 ServiceDescriptor .................................... 51 4.3.2 JobDescriptor....................................... 51 ii
Contents 4.3.3 Nano-CLCompiler.................................... 52 4.3.4 Example Nano-CL Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 4.4 IntegrationLayer ......................................... 53 4.4.1 Byte-codeDelivery.................................... 53 4.4.2 DataAggregation..................................... 55 4.4.3 CPU/DataCoordination................................. 55 NotationandAssumptions ............................... 56 Composition with Rate-Harmonized Scheduling . . . . . . . . . . . . . . . . . . . 57 Energy-SavingwithRHS ................................ 58 4.4.4 Network-wide batching using RHS . . . . . . . . . . . . . . . . . . . . . . . . . . 58 4.5 RuntimeArchitecture....................................... 60 4.5.1 Routing .......................................... 60 4.5.2 CodeInterpreter ..................................... 61 4.6 The sMapReduce Programming Abstraction . . . . . . . . . . . . . . . . . . . . . . . . . 62 4.6.1 The sMapReduce Programming Pattern . . . . . . . . . . . . . . . . . . . . . . . . 63 4.6.2 A Target Tracking Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 4.6.3 Mapping Applications for Mobile Nodes . . . . . . . . . . . . . . . . . . . . . . . 66 4.6.4 Features .......................................... 68 4.7 SystemDesign........................................... 69 4.7.1 sMapPlane ........................................ 70 4.7.2 ReduceOperation .................................... 71 4.8 EvaluationofNano-CF...................................... 72 4.8.1 Energy Savings with Rate-Harmonized Scheduling . . . . . . . . . . . . . . . . . 73 4.8.2 Performance Evaluation of the Runtime Environment . . . . . . . . . . . . . . . . 74 4.9 Summary.............................................. 75 iii
Contents 5 Redundancy Elimination across Applications 77 5.1 OverviewoftheApproach.................................... 79 5.2 ApplicationModeling ...................................... 82 5.2.1 Conversion to a sequence of nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 5.2.2 Modeling Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 5.2.3 Merging Packet Transmissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 5.3 Redundancy Elimination with Implicit Scheduling . . . . . . . . . . . . . . . . . . . . . . 86 5.3.1 String-Matching Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 5.3.2 Algorithm for generating a ρ-code (REIS-bytecode) . . . . . . . . . . . . . . . . . 88 5.3.3 ImplicitScheduling.................................... 90 5.4 Evaluation............................................. 90 5.4.1 Comparison of Online vs. Proposed Solution . . . . . . . . . . . . . . . . . . . . . 90 5.4.2 Relative Energy Savings in Processor Usage . . . . . . . . . . . . . . . . . . . . . 92 5.5 Limitations............................................. 94 5.6 SummaryandDiscussion .................................... 95 6 Hierarchical Assignment 97 6.1 HierarchicalAssignment..................................... 99 6.1.1 Problemformulation................................... 99 6.1.2 Constraints ........................................104 MemoryConstraint....................................105 NumberConstraint....................................105 6.1.3 ObjectiveFunction....................................106 6.1.4 Continuous approximation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 6.2 Gains with Hierarchical Scheduling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 6.3 RelatedWork ...........................................107 iv
Contents 6.4 Summary..............................................108 7 Network-Harmonized Scheduling 111 7.1 ModelandAssumptions.....................................113 7.2 Rate-Harmonized Scheduling for Packets . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 7.3 SingleBroadcastDomain.....................................116 7.3.1 Addressing the Hidden-Terminal Problem . . . . . . . . . . . . . . . . . . . . . . 118 7.4 Harmonization in a Multi-Hop Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 7.5 Real-TimePerformance......................................122 7.5.1 End-to-EndLatency ...................................123 7.5.2 End-to-EndDeadlines..................................124 7.6 Implementation..........................................126 7.7 ExperimentalEvaluation.....................................127 7.7.1 Real-Time Performance Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 7.7.2 Latency and Throughput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 7.8 Discussion.............................................134 7.9 Summary..............................................138 8 Conclusions and Future Research Directions 139 8.1 ResearchContributions......................................141 8.1.1 Programming framework for supporting multiple applications . . . . . . . . . . 142 8.1.2 Compile-time Inter-application Redundancy Elimination and Hierarchical Assignment..........................................143 8.1.3 Network-Harmonization to coordinate packets transmitted by multiple applications...........................................143 8.2 Validation of the Thesis Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 v
Contents 8.3 FutureDirections .........................................144 8.3.1 Multiple Applications on Dynamic Networks . . . . . . . . . . . . . . . . . . . . 144 8.3.2 Distributed Responsibility sharing among sensor nodes . . . . . . . . . . . . . . 145 8.3.3 A General Application Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 8.3.4 Context-aware application deployment . . . . . . . . . . . . . . . . . . . . . . . . 146 8.4 Prospective Vision: A Co-Operating System . . . . . . . . . . . . . . . . . . . . . . . . . . 146 8.4.1 Design Principles behind a CoOperating System . . . . . . . . . . . . . . . . . . . 148 Programming using CoS .................................148 TrulyDistributedDesign ................................149 OtherKeyFeatures....................................150 8.4.2 CoS Architecture .....................................151 Applications........................................152 Kernel ...........................................153 Drivers...........................................153 DataExchangePlane...................................154 8.4.3 Summarizing the Co-operating System . . . . . . . . . . . . . . . . . . . . . . . . 155 9 Bibliography 157 vi
List of Tables 2.1 A comparison of processor, memory and power specifications for different micro-controllers commonlyusedinsensornodes ................................ 17 2.2 Current drawn by the Firefly [1] sensor platform under various operation states with the corresponding battery lifetime under these states. . . . . . . . . . . . . . . . . . . . . 19 4.1 A list of the standard aggregation functions available in Nano-CF. . . . . . . . . . . . . 55 4.2 List of various byte-code types used in Nano-CF. These byte-codes identify the type of instructions in an application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 4.3 A list of various programming constructs available in the sMapReduce programming pattern. These constructs help an application to receive the network state and to leverage the device-level functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 4.4 A list of various operators available with sMapReduce that can be used to select a subset of suitable nodes from among a given list of nodes................. 65 4.5 Power consumption characteristics of a Firefly sensor node under different operating conditions of the processor and the radio. . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 4.6 Comparison of number of lines of code required by a programmer to write two different applications (shown in Figure 4.3), using the Nano-CL programming language and using the standard C for the Nano-RK operating system. . . . . . . . . . . . . . . . . . . 75 4.7 Comparison of flash memory requirements to store two different applications (shown in Figure 4.3) running individually on a sensor node, with Nano-CF as well as Nano-RK. 75
List of Figures 7.14 A graph showing the percentage of deadline misses over 20 iterations with respect to thesizeofthenetwork.......................................131 7.15 A graph showing the average radio-duty cycle over all the nodes after 20 iterations with the increase in the harmonizing period. . . . . . . . . . . . . . . . . . . . . . . . . . 132 7.16 A graph showing the average latency suffered by packets transmitted by nodes at differenthop-levels. .........................................133 7.17 A graph showing the number of packets received by the node with respect to time, shownonalogarithmicscale...................................133 7.18 An example topology where nodes at same hop level (eand f) have different parents, aand b, respectively, but lie within their wireless communication range (shown with the thick dotted line). In the NHS protocol, nodes eand fmay transmit simultaneously and can result in packet collisions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 7.19 First cycle in the bootstrapping phase, where nodes choose slots corresponding to their unique id’s (for the example shown in Figure 7.18). . . . . . . . . . . . . . . . . . . . . . 136 7.20 Second cycle in the bootstrapping phase, where nodes announce the slots they will choose from the next cycle onwards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 7.21 Third cycle in the bootstrapping phase, where devices choose slots such that potentially colliding slots can be avoided. Node fchooses slot 3 instead of slot 2. . . . . . . . . . . 137 8.1 Images showing various sensing equipments: from stationary sensing stations on the left sensing temperature, pressure (barometer) and humidity (hygrometer) to tiny sensor nodes with wireless communication capability. . . . . . . . . . . . . . . . . . . . . . . 140 8.2 An image showing a home appliance like a washing machine that can interact with a smart thermostat like the Nest. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 8.3 An illustration to show the process of programming with the help of a middleware, to emphasize the centralizing aspect. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 8.4 An illustration to show the process of programming a network of devices with the help ofaCo-operatingsystem.....................................150 xiv
List of Figures 8.5 A layered diagram showing typical architecture for a CoS. .................151 xv
List of Figures xvi
Chapter 1 Introduction Among the various milestones achieved by humankind in its history since the invention of the wheel, there is no denying that the invention of semiconductor electronics and, subsequently, computers are among the ones that have had the most significant impact on the world as we see today. Beginning with the vision of an “Intergalactic Computer Network” by J.C.R. Licklider in 1963 [7], the capability of computers to interact with each other has further revolutionized our lives with the development and large-scale acceptance of the Internet. Moreover, embedded computing systems, which were traditionally designed to be application-specific and standalone computers now also have the capability to communicate among each other and to the Internet. In principle, an embedded computer system1is a computer that is designed for a very specific application, interacts with its physical environment and is typically not suitable for general-purpose computing. Examples of such embedded systems include controllers in home appliances such as thermostats, washing machines or even dedicated computers in automobiles, airplanes and satellites. In recent times, however, the boundary between embedded systems and generic computers is getting blurred because of the increase in computational power and decrease in size and cost because of Moore’s Law [8]. Modern mobile phones, also called smartphones, are a prime instance of “the merge” of embedded systems with communication capabilities and high computing power. On the other hand, Moore’s law has also led electronic devices to become smaller in size at such 1Embedded-computer systems are also more commonly referred to as embedded systems
Chapter 1. Introduction a low cost and low power consumption that it is expected that almost every object around us can become a smart embedded system. Already, devices around us are becoming increasingly smarter and many of those devices have sensors to measure physical quantities that can allow them to be aware of the surrounding environment and take better decisions while interacting with that environment. Next-generation applications of such embedded systems is expected to involve high-degree of internetworking of devices, possibly with an aim to accomplish the vision of Internet of Things. In this view, Wireless Sensor Networks (WSNs) have been playing an important role both as a technology-incubator as well as a test-bed for the networked embedded systems of the future. 6LoW- PAN [9] is a standard in this direction that can bring Internet Protocol (IP) connectivity to small embedded devices in a similar way as general-purpose computers of today are interconnected via the Internet. Despite wireless sensor networks being a very active research field and a number of very highly-rated conferences and journals catering to this area, most of the works are limited to laboratory test-beds with very little adaptation to real-world deployments. One of the main reasons behind this is that the deployments are typically very application- or goal-specific to the problem being addressed. In order to promote fast adoption of sensor networks for practical usage, they should be developed as a long-term infrastructure technology with support for multiple applications from independent users, rather than as application-specific deployments for short-term use. Therefore, in this dissertation, we propose a multi-dimensional approach to deploy more than one application on a sensor network and simultaneously reduce the resource consumption at various levels. Such multi-application or multipurpose embedded systems are quite in contrast to the early vision of computers as evident from the following quote by J.C.R. Licklider [10]: Men are noisy, narrow-band devices, but their nervous systems have very many parallel and simultaneously active channels. Relative to men, computing machines are very fast and very accurate, but they are constrained to perform only one or a few elementary operations at a time. Men are flexible, capable of “programming themselves contingently” on the basis of newly received information. Computing machines are single-minded, constrained by their “pre-programming”. Through the technologies we built and the optimizations we propose in this dissertation, we attempt to revise this widely-held notion of application-specific and inflexible networked embedded systems into an infrastructure technology that can cater to different needs of many users simultaneously. In 2
1.1. Background on Wireless Sensor Networks Gateway' Wireless' Links' Figure 1.1: A typical sensor network with several Firefly [1] sensing platforms communicating over wireless links (shown with symbolic line-connectors). The network topology is a tree topology with a gateway node as the root. The gateway is connected to a PC, which acts as a router to the Internet. this dissertation, we focus mainly on Wireless Sensor Networks (WSNs) as a representative technology. 1.1 Background on Wireless Sensor Networks With the capability to communicate over wired or wireless links, embedded systems can create a complex ecosystem with an unfathomable potential, and Wireless Sensor Networks (WSNs) bring connectivity closer to the physical world by measuring and monitoring the physical quantities such as temperature, pressure, humidity and light intensity. This is made possible through inexpensive and small hardware modules with radio transceivers. Not only do wireless sensor networks have the potential to improve several day-to-day and fundamental systems such as transport, power distribution, agriculture etc., by enabling large-scale monitoring, they can also have an important role as test-beds or technology incubators for materialization of the concept of the Internet of Things. 3
Chapter 1. Introduction Wireless Sensor Networks consist of a large number of tiny hardware devices called sensor nodes2 that can form an ad-hoc mesh network so that the values sensed by individual devices can be collected at a sink (or gateway or root) as shown in Figure 1.1. Wireless Sensor Networks have been, and are currently being, used for a variety of applications and purposes that were inconceivable with traditional sensing methods of using large sensing stations requiring manual deployment and manual data-collection. Wireless Sensor Networks are designed to be operated autonomously once deployed, (potentially) without the need for any human intervention. There is a large variety of applications of sensor networks, and we briefly list some them below: Environmental Sensing. Remote sensor networks have been deployed to monitor natural phenomena such as volcanoes [11], health of redwood trees [12] in California, US or underwater phenomena such as coral-reefs and fisheries [13, 14]. Structural Health Monitoring. Monitoring the health of civil infrastructures such as buildings [15], bridges [16], underground mines [17] or factory equipment [18] are some of the most popular applications of sensor networks. Industrial Sensing. Industrial processes need to monitored regarding various parameters for smooth functioning of assembly lines and safety concerns [19, 20]. Understanding Social Behavioral Patterns. Sensor networks may enable the understanding of the social behavior with a human-centric approach where humans carry a portable sensor [21, 22]. Human health monitoring is also another example of human-centric sensing [23]. Disaster Management. Sensor networks are helpful in disaster situations such as forest-fire monitoring [24] or search and rescue operations [25]. Building Monitoring. There are several other applications that help in accomplishing smart-buildings and reducing the energy consumption. For example, building automation [26], energy-audit [27] and data-center monitoring [28]. In this dissertation, we focus on sensor networking applications mainly related to building monitoring. In such applications, various sensors are permanently deployed inside buildings to observe 2A more detailed description about various platforms used as sensor nodes is provided in Chapter 2 4
1.2. Motivation and Challenges energy consumption, temperature, occupancy, humidity and noise etc., and different users would benefit in using that infrastructure to run their independent applications simultaneously. 1.2 Motivation and Challenges Modern sensor networking platforms are complex devices with multiple types of sensors, allowing independent users to employ one or more sensors on each device for creating network-level applications. Let us consider the example of a university campus sensor network deployment, such as the Sensor Andrew [29] project at the Carnegie Mellon University. Sensor Andrew is deployed across several buildings to monitor physical properties of the environment such as temperature, humidity, smoke or light. A diagram of a sample building with a variety of networked sensors is shown in Figure 1.2. To facilitate the appropriate use of such a network, it is beneficial to provide support for multiple applications from users with different goals and backgrounds such that the network infrastructure can be treated as a multi-purpose sensor network [30]. For example, a building manager may be interested in collecting the temperature values from the sensors for a fine-grained temperature control, while a civil engineer may want to find the correlation between temperature and humidity for optimizing a building’s HVAC system. Furthermore, a security officer may want to monitor the fire alarms periodically. With multi-purpose sensor networks, several varied applications may be concurrently supported on the same infrastructure. In this dissertation, we address various challenges that emerge from allowing multiple applications to execute on a shared sensor network infrastructure. There are several advantages in enabling such multi-purpose sensor networks, including improving cost effectiveness, enlarging the user-base of the sensor networks, and enabling the integration of sensor networks with other large-scale technologies. With multiple applications, the sensor network infrastructure can be utilized better, in a cost-effective and in a collaborative manner by independent users. Moreover, multi-purpose sensor networks can provide seamless integration with larger-scale technologies such as the Smart-Grid or the vision of Internet of Things. As an example, power companies may also want to deploy suitable applications on sensing devices installed in buildings so that they can access (limited) data about usage patterns of various appliances. This data can help the power companies to schedule load-balancing strategies with better efficacy. In addition to the advantages from the application perspective, multi-purpose sensor networks also encourage users from diverse 5
Chapter 1. Introduction Figure 1.2: An example of an indoor sensor network with various types of sensors deployed at different locations inside a building. Sensor Andrew is an example of such a network, but spread across multiple buildings. backgrounds to develop applications in a convenient manner, thereby promoting multi-disciplinary research. In spite of the advantages discussed earlier, several challenges arise with multiple applications executing on sensor networks, mainly due to the resource-constrained nature of sensor nodes. As the primary design principle behind sensor nodes is to keep the hardware cost low and to attain longlife with relatively cheap batteries, reducing the average energy consumption has been one of the foremost challenges in this area of research. With multiple applications, several new challenges arise that need to be addressed for the proper management of the network resources, and are discussed below. 1.2.1 Programming Support Programming sensor nodes individually is a time-consuming and complex procedure, so several macro-programming approaches and middleware have been proposed in the past to install applications at the network-level, such as Regiment [31], Mate [32] and TinyDB [33]. Except for a few 6
1.2. Motivation and Challenges solutions proposed recently [3], not many approaches support deployment of multiple concurrent applications at a network-level. Considering the example of Sensor Andrew, users from diverse technical backgrounds may benefit from a middleware layer that helps them program the network at an abstract higher level. A conventional macro-programming framework may not allow more than one user to independently program the sensor network for handling these kinds of applications simultaneously. To support multiple applications, several additional aspects have to be managed regarding programming abstractions, application installation, execution and data delivery. 1.2.2 Inter-application Redundancy Most sensor networking applications are designed with the goal to sample one or more sensors, conduct some signal processing on the sampled data, and then share it with other nodes or a base-station to accomplish a distributed logic. In the case of more than one such application, there is a likelihood of redundant sample collections by different applications causing unnecessary energy consumption. It is observed that reading a sensor value typically involves accessing an Analog-to-Digital Converter (ADC) module on a microprocessor, for converting the analog sensor value into a digital format, and storing into a register or local memory. This process of sampling a sensor can consume about 2–3 orders of magnitude more processor cycles than a simple memory-based instruction, thus increasing the processor usage on a sensor node. 1.2.3 Conforming to Resource Limitations With more than one application deployed on sensor nodes, various resources tend to be used more frequently. Finding a balance between the application requirements and the available resources is a challenge. There is a need to optimally assign resources among applications, such that application requirements are met and the overall resource consumption is reduced as much as possible. 1.2.4 Network Coordination In addition to resource optimization on individual nodes, several issues still exist in the networking layer when multiple applications execute on sensor nodes. It is often the case that applications release 7
Chapter 1. Introduction •In Chapter 4, we describe our proposed Nano-CF programming framework to support multiple applications on sensor networks. Nano-CF allows a programmer to write a network-level application and the framework transparently handles the application delivery and the runtime executes it on each node on top of the Nano-RK operating system. •In Chapter 5, we present a compiler optimization approach based on the observation that independent applications developed in Nano-CF may issue redundant sampling requests leading to the over-consumption of resources. We propose the design of a compile-time approach called REIS that finds maximum overlap across applications such that redundancy is eliminated. •We then extend the REIS approach further with a hierarchical assignment described in Chapter 6 scheme that instead of finding redundancies across all the applications, finds it across a subset of applications such that the redundancy elimination is maximized while satisfying the resource constraints of sensor nodes. •While expanding the focus from node-level optimizations to network coordination in case of multiple applications, we propose Network-Harmonized Scheduling in Chapter 7 that aligns the packet releases from multiple applications along periodic boundaries, and then harmonizes them across the network. •Finally, in the last chapter, we conclude this dissertation with a summary of contributions and a discussion of future work. As a part of future research directions, we also provide a vision of a new operating system paradigm for sensor networks called Co-Operating System that is distributed by design and allows application development at a larger scale than node-level. 14
Chapter 2 Background As we briefly described in the previous chapter, wireless sensor networks consist of a large number of sensing devices connected to each other via wireless links. Wireless connectivity eases the deployment of a sensor network, as laying wires for a large number of devices can be unpractical and expensive both in terms of cost and man-hours. With wireless communication support, the devices can be deployed in remote terrains with relative ease and old buildings can also be retro-fitted without the need for re-wiring. Furthermore, the use of batteries to power wireless devices is a logical choice to completely remove the need for wiring. On one hand, batteries and wireless communication enable sensor networks to be used effectively with an ease of deployment, but on the other hand, battery-powered and wireless operation are two of the most important factors that bring forth a broad range of challenges in all the aspects of sensor networking. In this chapter, we briefly outline some of the many fundamental technologies that are employed in sensor networks to address the challenges that mainly are manifestations of battery-powered and wireless operation. Throughout the research efforts presented in this dissertation, we have made use of a majority of these technologies that include hardware platforms, operating systems, programming frameworks and networking protocols.
Chapter 2. Background Microcontroller Radio Battery Sensor 1 Sensor 2 Sensor n Memory Figure 2.1: A schematic diagram of a sensor node 2.1 Platforms Several hardware platforms have been developed in the past as prototype devices for wireless sensor networks, and many such devices are commercially available. Some of the popular choices for general-purpose sensor networking platforms include Mica2 [43], MicaZ [44], Sun SPOT [45], TelosB [46] and Firefly [1]. There are several other experimental platforms that serve applicationspecific goals, such as energy-harvesting [47, 48], structural monitoring [16], industrial sensing [19], data-center monitoring [28, 49] or smart homes [50]. In this dissertation, we limit our description to general-purpose sensor platforms, as our solutions are built for such devices. Various terms are used interchangeably to refer to a sensing platform as explained next: Individual hardware devices in sensor networks are typically referred to as motes, and in the larger context of a network of interacting motes, each device is also referred to as a sensor node, or more commonly as a node. Even though a sensor node consists of one or more sensors, a microprocessor and a radio transceiver among several other peripherals, the term sensor is also used interchangeably for a sensor node, as one of the key jobs of a node is to sense the environment and share it with other devices. Sensor nodes are highly energy constrained devices, powered either with the help of batteries or energy harvesting systems such as solar panels. As a result, sensor nodes are designed with highly resource-constrained hardware components due the limitations of the power-source. A typical sen- 16
2.1. Platforms Table 2.1: Comparative specifications of micro-controllers commonly used in sensor nodes Parameter TI MSP430aAtmel ATmega1281 Atmel ATmega128RFA1 Architecture 16 bit 8 bit 8 bit Max. Frequency 16 MHz 8MHz 16MHz RAM 10KB 8KB 16 KB Flash 48KB 128KB 128KB Sleep Current 5.1µA 5µA 5µA Active Currentb1.8mA 10mA 4.1mA aSpecifications for MSP430F2611 used in TelosB motes bat 8MHz and 3V sor node consists of a low-powered micro-controller that is connected to a relatively simple and lowpowered radio-transceiver. Several different sensors for monitoring temperature, pressure, humidity, acceleration, motion, etc., are also provided on board, and almost all platforms have expansion ports to connect to other specialized sensors. A schematic diagram of a typical mote with its components is shown in Figure 2.1. Firefly and MicaZ motes use the Atmel ATmega1281 micro-controller [51], and TelosB motes, on the other hand, use the Texas Instruments (TI) MSP430 [52] micro-controller. Both these micro-controllers are low-powered and have an 8 bit architecture with on-chip memory and flash. The Atmel ATmega1281 micro-controller has only 8 Kilo Bytes (KB) of RAM and can operate at a maximum frequency of only 8 MHz. The capacity of the on-board flash to store the firmware is about 128 KB, which means that the entire software stack should fit within this limited storage. These specifications are several orders of magnitude lower than that for a modern personal computer or even a modern handheld smartphone. The Moore’s law is expected to help in reducing the size, power requirements and cost rather than improving the computational capabilities. Newer designs of motes, like the Firefly version 3, use System-on-Chip (SoC) solutions such as the Atmel ATmega128RFA1 [40] that has the processor and the radio transceiver on the same chip, thereby reducing the size of the motes and allowing more power-efficient designs. Figure 2.2 shows a snapshot of the latest Firefly mote with an expansion board consisting of a variety of sensors. Table 2.1 lists some relevant specifications of TI MSP430, ATmega1281 and Atmel ATmega128RFA1, to emphasize the limited memory and computational power available with sensor nodes. Wireless communication among the nodes in a network is achieved using a low-power Radio- Frequency (RF) transceiver such as the Chipcon CC2420 [53]. Even if designed for low-power opera- 17
Chapter 2. Background Audio! Light! PIR- Mo/on! Humidity! Pressure! Liquid-/- Relay! Accelera/on! Temperature! Calibra/on- EEPROM! Figure 2.2: A Firefly version 3 node with a sensor expansion board. tion, the radio is still the single largest energy consuming peripheral on a sensor node. In most cases, the power consumption by the radio can be up to 3-4 times compared to that of the processor. For CC2420, active current drawn during the transmission of a packet is 17.4 milliamperes (mA) and is counter-intuitively lower than that for reception, which is 19.7 mA. The higher energy requirements of the radio make it important to design efficient communication-layer and networking mechanisms for sensor networks. If a sensor node is powered with a pair of off-the-shelf AA batteries of about 2000-3000 mAh capacity each, a continuous (always on) operation will yield only a battery life of about 2-3 days. This would mean that the batteries would need to be changed or recharged very frequently, making remote and/or large sensor network deployments impractical. In order to increase their lifetime, sensor nodes are typically operated with a very low-duty cycle of the order of 1% or 0.1%, such that sensor nodes remain in the sleep mode for a majority of the time. In this way, the sensor nodes can operate for a longer duration up to several months with the same batteries. Table 2.2 lists the current drawn and the corresponding battery lifetime for a Firefly sensor node under various operation states, when powered by two 2750 mAh AA batteries. Reducing the communication overhead and maintaining a very low duty-cycle are primary concerns while designing the software layers of sensor networks aiming for a long operational-lifetime with small and inexpensive batteries. Hence, miniziming the energy consumption and improving the energy-efficiency is a fundamental principle based on which viable sensing systems are built. 18
2.2. Sensor Network Software Architecture Table 2.2: Typical current drawn and corresponding battery lifetime for a Firefly [1] sensor platform under various operation states. Firefly Operation State Current Consumption Battery Life Processor Active 7 mA 17 days Active with Transmission 24.4 mA 4.9 days Active with Reception 28.8 mA 4.6 days Idle 2 mA 60 days Sleep 70 µA4.68 yrs 2.2 Sensor Network Software Architecture Sensor networking platforms such as the MicaZ and the TelosB, mentioned in the previous section, are highly resource-constrained. However, they are complex devices with several peripherals that can easily support a small operating system, custom communication stacks and one or more software applications. Programming the sensor nodes by directly writing the application logic on the system flash (colloquially referred to as bare-metal programming) without an operating system can be a daunting task even for skilled developers. To circumvent this challenge of developing software for sensor networks, suitable programming support has been developed in the form of various operating systems and network-level programming abstractions, as discussed next. 2.2.1 Operating Systems One of the most important software component in sensor networking is an Operating System (OS), which provides several convenient abstractions to ease the application development. An OS also handles key responsibilities such as scheduling the tasks, process management, interfacing with hardware through device drivers and power management. In comparison to general-purpose computers, where operating systems handle several additional responsibilities such as memory management, virtual memory, graphic user-interface management etc., sensor networking operating systems [54, 55] are limited in features due to the highly resource constrained hardware of sensor nodes. The application-specific nature of sensor networks results in a wide variety of the underlying hardware, and therefore, operating systems play an important role in hiding this heterogeneity from the applications. Consequently, operating systems are imperative for providing hardware abstraction, 19
Chapter 2. Background management of the limited resources and enabling communication with the other devices in the network. Operating systems for sensor networks are designed to satisfy several different requirements, and some of them are listed below: •Providing Hardware Abstraction: One of the foremost goals of an operating system is to provide abstractions to the underlying hardware, and it becomes even more important for sensor networks due to their heterogenous nature. Suitable software modules and device-drivers are included in the OS for sensor nodes to facilitate the interaction with peripherals such as sensors, actuators and the radio transceiver. •Power Management: As sensor nodes are powered using batteries, they have a limited energy source and managing the energy requirements becomes another important responsibility of the operating system. In addition to providing explicit power-management control to applications to turn peripherals off when not in use, the operating system can also implicitly turn-off the unused devices even when applications are not designed to do so. •Resource Management: Sensor nodes are resource constrained in terms of processing power, memory size and networking bandwidth, so the operating system ensures that resources are fairly used among various tasks. If some cases, the operating system can also enforce fair resource-usage by preempting a misbehaving task. •Handling Communication: The operating system provides a configurable and modular communication stack to enable the applications to interact with the other devices. To achieve this goal, operating systems include Application Programming Interfaces (APIs) to allow programmers to use various communication protocols with ease. •Task Scheduling: The operating system is also responsible for scheduling the tasks on a sensor node while considering the application requirements such as minimizing latency, ensuring fairness and maximizing the throughput. Applications with real-time constraints may require a real-time scheduler and the operating system can provide support for such a scheduling mechanism. Various specialized operating systems have been developed in the past such as TinyOS [56], Con- 20
2.2. Sensor Network Software Architecture tiki [57], Mantis [58], LiteOS [59] or Nano-RK [35]. There OSes address the requirements listed above in different ways. TinyOS [56] is one of the first and one of the most popular operating systems that is designed for sensor nodes. TinyOS is small in size (about 400 bytes kernel) and provides a component-based interface for specifying the interaction of various devices. A TinyOS configuration consists of the application, the corresponding operating system services and the scheduler in form of components. All the components are glued together to form a static/monolithic image that runs on a sensor node. A TinyOS component is formed with a composition of three abstractions: commands, events and tasks. Commands are used to trigger other services and events, in turn, signal their completion. In this way, TinyOS has an event-driven design with asynchronous events to handle computational entities that are called tasks. Early versions of TinyOS had a simple run-to-completion based First- In First-Out non-preemptive scheduler. A newer version of TinyOS with TOSthreads [60] supports a threading model with more flexibility. TinyOS uses the NesC [61] programming language for the specification of components and their concurrency model. On the other hand, the Nano-RK [35] operating system has a time-triggered and event-triggered execution model. The main highlight of Nano-RK is its prioritized resource-kernel [62] approach where the kernel can enforce resource-usage limitations upon different tasks in the system. For example, if a task uses more processor cycles than its pre-allotted share, then the kernel can preempt the task and allow its execution only in its next cycle. The resource-kernel model of Nano-RK is capable of ensuring fair-sharing of resources among competing tasks; that is why we use Nano-RK as the base operating system for building the Nano-CF framework for multiple network-level applications on a sensor networking infrastructure as described in Chapter 4. Contiki [57] is another popular operating system with a large user-base and support for the 6Low- PAN [9] networking standard. Contiki has an event-driven execution model like TinyOS, but has a modular design with support for dynamic loading/unloading of modules. Contiki supports both synchronous and asynchronous events, that helps in achieving a better timeliness behavior where synchronous events get scheduled immediately and asynchronous events follow a queue. Contiki also supports a rich set of communication protocols including various medium access and higher- 21
Chapter 2. Background layer network protocols. We have used Contiki in this dissertation for the implementation of the Network-Harmonized Scheduling protocol described in Chapter 7, mainly because it supports varied hardware, supports full Internet Protocol (IP) connectivity and makes network simulation convenient with the COOJA [63] simulator. 2.2.2 Programming Support Programming a new hardware device is typically a significant deterrent particularly for researchers not familiar with embedded systems programming, and the difficulty increases several-fold if the devices need to communicate, for instance, to implement a distributed application. In the context of embedded systems and wireless sensor networks, usability and programmability are closely related as the user interaction with the devices happens mainly via programming interfaces rather than a graphic user interface as in the case of general-purpose computers. The most basic way of programming sensor nodes is to connect them individually to a computer via a serial connection and uploading an application-specific firmware. Programming a large network in this manner can be very time-consuming, as it may involve collecting all the sensor motes from the field of deployment, programming them and then deploying them back. This method of programming is referred to as Manual Programming in the classification we provide later. On the other hand, to facilitate a faster and large-scale application deployment, it is useful to program the network as a whole at a higher level. This mechanism of programming the network at a larger- or macro-scale is referred to as macro-programming. The spectrum of macro-programming approaches range from delivering application-specific virtual machines to individual nodes like in Mat` e [32] to an abstract high-level programming like Logical neighborhoods [64] or Regiment [31]. Typically, the ease of programming increases with an increase in abstraction but it comes at the price of flexibility. We, therefore, divide the different programming approaches into following classes: •Manual Programming: Programming sensor nodes over bare metal or an operating system by manually connecting a sensor node to a computer and flashing a firmware. •Over-the-Air Virtual Machine: Creating a node-level virtual machine and delivering the binary or byte-code to the nodes over-the-air. 22
2.2. Sensor Network Software Architecture Manual& Programming& Over0the0air& Virtual& Machine& Middleware& Approaches& Query0based& Approaches& Data& Repor?ng& Ease&of&Programming& Flexibility& Figure 2.3: Ease of programming vs. flexibility in various classes of programming approaches. •Middleware: Allowing the development of network-level applications as one application while hiding the network complexities. •Query-based approaches: Writing SQL-like queries to request simple/aggregated data from the network. •Data Reporting: Storing all the sensor readings periodically in an external database and accessing them when required. It is typically used in high-level Service-oriented Architectures (SoA). Figure 2.3 shows different classes of programming methods for sensor networks. The ease of programming increases from left to right, but the flexibility follows the opposite direction. Most macroprogramming schemes are limited to application-specific network operation, and our proposed framework called Nano-CF (described in Chapter 4) supports multiple independent applications with several resource optimizations at the node- and network-level. A more detailed discussion of the various state-of-the-art macro-programming approaches is provided in Chapter 3. Reprogramming the devices or adding new applications after the devices have been deployed is still an active research challenge, and require a paradigm shift in the way devices are programmed and applications are installed. This is particularly challenging because the number of sensor devices and their ability to interact has been steadily increasing. Hence, providing the support for dynamic application deployment and its standardization is of paramount importance for increasing the outreach of smart sensing devices to diverse users, much like the concept of app-store has revolutionized the way we use mobile phone today. 23
Chapter 2. Background Node Deployment Sensor nodes can typically be deployed in harsh climates and remote terrain. Even urban sensor deployments involving structural-health monitoring or industrial sensing can suffer from harsh operating conditions, where deployment is challenging. Nodes can be deployed randomly over a uniform field such as in agriculture monitoring or carefully placed at specific target points such as while monitoring the health of a bridge. In both such types of deployments, creating a optimal topology is a challenge. The routes have to be established such that all the nodes have connectivity. Network Load Balancing While ensuring connectivity is important, it is possible that some nodes may have to handle more packets to forward than the others, thus leading to more energy consumption. If possible, the routing scheme is entrusted to find such bottleneck nodes and create new routes to ensure load balancing. Fault Tolerance Wireless links can be intermittent, unreliable and asymmetric requiring networking protocols to provide redundant links or the transport layer to trigger retransmissions. Routing takes care of such issues depending on the application requirements such that varied degrees of fault-tolerance can be provided. Scalability Routing protocols either establish static links at the start of the network or periodically refresh the routes or use flooding mechanisms where data is forwarded and re-forwarded to all the nodes in the network. In the case of new devices joining the network or an old device leaving, the network performance is different based on the type of routing used. Data Aggregation If data needs to be collected at one or more sink nodes in the network, the number of packets to be forwarded by a node grows exponentially with the depth of the node in the network tree. The routing layer can make it possible to aggregate data through the network so that the number of packets do not accumulate at each hop. For example, if the application requires basic aggregates such as Max, Min, Sum or Average, then instead of sending all the raw data, each node can only forward a local aggregate based on the data received by it. AdHoc On-Demand Vector (AODV) [84] and its variants are one of the most popular approaches to establish routes by finding shortest paths in the network graph. Such a routing protocol is then used for collection of data from all the nodes in the network at a root node. Resource-constrained sensor networks have severe energy constraints so protocols such as Trickle [85] adapt the rate of 30
2.3. Communication and Networking transmission of updates to prevent incessant flooding in the network. For example, Collection-Tree Protocol (CTP) [86] finds routes using and AODV-like approach and then adapts them dynamically using a rate-control mechanism inspired from Trickle. For implementing the Nano-CF programming framework, we used the BMAC-protocol with the AODV routing protocol to deliver applications to remote nodes and to collect data from them as well. Further details of the related protocols are provided in Chapter 3. Summary In this chapter, we provided a brief background on various technologies that are used in sensor networks in general. In particular, we stressed the ones we employed in the solutions proposed throughout this dissertation. We covered a wide range of technologies from hardware platforms to operating systems and networking protocols. 31
Chapter 2. Background 32
Chapter 3 Related Work In order to acheive the goal of supporting and optimizing the execution of multiple applications on sensor networks, we have proposed a three-fold approach that includes a programming framework, an optimization scheme to eliminate redundancies and a network protocol to coordinate packet transmissions. A large number of projects has been undertaken in the past in these three broad domains. Hence, in this chapter, we summarize the existing research addressing the following areas while contrasting them with our proposed approach. (a) programming of sensor networks, (b) redundancy elimination, and (c) networking protocols. 3.1 Programming Sensor Networks Designing and deploying applications on a sensor network can be challenging because of the geographical spread of the sensor nodes, as well as the heterogenous nature of the hardware and software. In a traditional sense, the sensor networking applications are programmed at the operating system level, where a programmer may have to implement a distributed logic while having
Chapter 3. Related Work working with very low-level details. This method makes it difficult to create large-scale applications quickly, especially for users from non-computer-engineering backgrounds. Researchers have long focused on developing programming tools that can help users from varied backgrounds to develop applications for sensor networks at a macro scale; this process of programming a set of nodes in a network is typically referred to as macro-programming. There is a wide spectrum of such macroprogramming tools serving varied applications that range from programming frameworks designed to deploy application-specific virtual machines on sensor nodes to high-level programming abstractions that provide an abstract view of the network to a programmer. We will now discuss some of these programming tools classified into programming frameworks, middleware and programming abstractions. 3.1.1 Over-the-Air Programming Frameworks Several programming frameworks have been proposed in the past that allow a user to deploy applications on sensor nodes over the wireless network rather than flashing a firmware by connecting a node individually to a computer. This method of programming sensor networks is referred to as over-the-air or in-network programming. Mat` e [32] is one of the earliest proposals that delivered an efficient virtual-machine to each sensor node running TinyOS, rather than sending an entire binary of a few kilobytes over the air. Virtual-machines in Mat` e are created using a special programming language called TinyScript such that a typical sensor networking application can fit within a few tens of bytes. A virtual machine is received and executed using a byte-code interpreter running on top of TinyOS instances on each sensor node. A simplified architecture of Mat` e is shown in Figure 3.1. An application created by a user is converted to byte-code, which is in turn split into one or more code-capsules of 24 bytes each, such that one capsule can fit in one packet. The capsules corresponding to an application are sent to sensor nodes over the wireless network and then they are stitched again to form the virtual machine. The Mat` e byte-code interpreter then executes the virtual-machine. The overall design and architecture of our proposed Nano-CF framework is similar to Mat` e, but in contrast, Nano-CF supports multiple applications and allows a programmer to specify a set of nodes that receive and execute a particular application. Kairos [87] is a similar macro-programming approach that allows a programmer to write a highlevel code specifying node interactions. It provides constructs like get available nodes() and sleep() 34
3.1. Programming Sensor Networks TinyOS Operating System Byte-code Interpreter (Matè) Capsule1 Tiny-Script User Application Wireless Network Capsule2 Capsule3 Capsulek Figure 3.1: A simplified architecture diagram of the Mat`e virtual machine for sensor networks to identify the presence of nodes in a network and control their active/sleep behavior, respectively. The high-level code is broken into node-level binaries that are delivered to all the nodes in the network. More recently, solutions like PyoT [2] provide macro-programming support based on popular and standard protocols like 6LowPAN [9] and the Constrained Application Protocol (CoAP) [88]. Since it is built on top of well-known protocols, PyoT is suitable for rapid and interoperable application development. PyoT uses the Python scripting language as the shell scripting interface to create applications. It also provides a graphical web-interface for visualizing the network status and polling sensor values directly. The architecture of PyoT is shown in Figure 3.2. A PyoT worker node manages one sensor network and also acts as interface link between the sensor network and the Internet. The control center manages the overall network and provides the user with a view of the network through the web-interface. The scheme conceptually closer and nearly contemporaneous to our Nano-CF programming framework is SenShare [3, 89] that is also designed to support multiple applications on a sensor networking infrastructure. SenShare supports multiple TinyOS applications on sensor nodes through a hardware abstraction layer that assembles low-level components into binaries to be executed on the underlying operating system. One of the major disadvantages of SenShare as compared to Nano-CF is that it has only been implemented for the Imote2 [90] sensor nodes running Linux operating system and it may be impractical for low-powered devices. Nano-CF, on the other hand, allows multiple applications 35
Chapter 3. Related Work Web$ Interface/Shell0 PyoT0Worker0 Node0(PWN)0 Database0 Control0Center0 IoT0Network0 Figure 3.2: Architecture diagram of the PyoT macro-programming solution, as presented in [2] TinyOS'App' Run,me'API' Mul,tasking'OS' Run,me' Network'I/O' Sensor'I/O' Applica,on' Control' TinyOS'App' HAL'Layer' Sensing' Network' Clock' Run,me'API' Sensing' Network' Clock' Figure 3.3: Architecture diagram of SenShare multi-application programming framework, as presented in [3] to be deployed and supported on resource-constrained sensor networks, as recent versions of sensor node operating systems have support for multiple tasks [60, 35]. The process of reprogramming all sensor nodes incurs a large overhead as multiple application packets may need to be sent to individual nodes. Compressing the size of reprogramming packets [91] and incrementally programming each node [92] are some of the techniques proposed for reducing this overhead. The frequency of reprogramming the nodes is typically lower than that of data communication, hence it is more beneficial to optimize the resource consumption during the normal use of the network. 36
3.1. Programming Sensor Networks 3.1.2 Middleware Approaches Addressing the challenge of programming sensor nodes from a higher perspective, other works such as [93, 94, 95] describe middleware for facilitating the development of sensor networking applications on individual nodes. One of the most common middleware systems for generic computer systems, CORBA [96] hides the location of remote objects and hides the application’s interactions with the remote objects. The Lime middleware [97], designed for mobile and ad-hoc networks, abstracts the underlying network and uses tuple-based interaction with the devices. Similar middleware have been designed for sensor networking, where network details are hidden. Often times, middlewarebased approaches are limited in the flexibility of reprogramming, but act as an interface layer between sensor-networking primitives available to the applications and the underlying networking infrastructure. For example, Mires [94] is a message-passing middleware with a publish/subscribe model for collecting data from the sensor network; a high-level user application can select (subscribe to) a desired data that is published by the sensors. The lower level intricacies of connecting the sensors, establishing the routes and collecting the data are handled by the middleware, and are transparent to the user. This is similar to the DSWare approach [95] that allows a user-application to query the sensor network by creating an event in a high level programming language. TinyLime [93], shown in Figure 3.4, is inspired from the Lime middleware, and is adapted to a more complex scenario where mobile base-stations collect data from a network of stationary sensor nodes. The users (clients) use a client host to connect to one or more base stations to exchange data in the form of Lime tuples. The base station then exchanges the information with the motes that are directly connected to it. Query-based approaches for reprogramming sensor networks such as [33, 98] provide declarative programming expressions for processing data gathered by the sensor nodes. These schemes are useful to systems where different types of data are required frequently for monitoring and inference purposes. TinyDB [33] allows the use of SQL-like queries for getting aggregated responses from the sensor network in a transparent fashion. A TinyDB query consists of a clause of the type: SELECT-FROM-WHERE-GROUPBY. The functions of these clauses are similar to that of SQL. A user can specify a query in the following form: SELECT nodeid, light, temp 37
Chapter 3. Related Work Client'Host' MoteLime' Tuple'Space' Base'Sta5on'Host' Lime'<7>'Mote' Transforma5on' Mote'Access' Lime'Tuple' Sharing' Reachable'Motes' Figure 3.4: Architecture of the TinyLime middleware showing simplified interactions between a client, a mobile base station and the sensor motes. FROM sensors SAMPLE PERIOD 1s FOR 10s TinyDB also has in-network aggregation mechanism to reduce the amount of data and number of packets that needs to be exchanged in the network. Such in-network query processing approaches are advantageous in applications where frequent processing of new but simple queries is required. These schemes are convenient to use, but not very scalable, as individual programming of every node may be required to implement a new query. Most of the middleware solutions discussed so far, hide the network interactions from a user, and provide a convenient user-interface to access the required information from the network. Such schemes are, however, limited in the flexibility and are suitable mainly for data collection applications. They are not appropriate if the applications require more control (for example, changing the device interactions in the network). Moreoverer, access from multiple users can be implemented only in terms of sequential queries, which limits the possibility of efficiently using the underlying multi-tasking operating systems such as Contiki or Nano-RK. 38
3.1. Programming Sensor Networks 3.1.3 Abstractions for Macro-programming High-level programming abstractions like Regiment [31] and Hood [99] allow programmers to view the network as a set of abstract subnets based on neighborhood, proximity to an event, sensor reading or a combination of these. These abstractions allow convenient selection of nodes for reprogramming, data collection, and aggregation; thereby optimizing the overall communication in the network. Regiment is a macro-programming language and a runtime framework that presents the sensor network as a set of distributed, time-varying signals to a programmer. The signals can correspond either to the sensor readings, results of localized computation/signal processing or an aggregate value across a set or region of sensor nodes. Regions can be defined in terms of geographical area, network topology or capabilities (e.g., all the nodes with humidity sensors). Regiment uses a Functional Reactive Programming (FRP) model that includes a function rmap(f,s) to map a function fto a region of all sensors given by s. On the other hand, the Hood programming abstraction allows a node to identify a subset of nodes around it based on a variety of criteria and share data with those nodes. Hood includes several programming interfaces that allow powerful-yet-simple interactions among devices to help in implementing large-scale and distributed applications. These interfaces allow setting of key properties of the network, such as attributes (e.g., sensor type), neighborhood size, read operation and write operation with other sensor nodes. Hood also incorporates a code-generation tool that generates the interfaces using the generate commands in nesC. Logical Neighborhood [64] is also another powerful abstraction that replaces the conventional physical neighborhood defined based on communication range with a logical one, where the proximity of a node can defined by applicative information. Logical neighborhoods are specified declaratively using the specifically designed Spidey language. Our proposed framework, Nano-CF, can easily make use of such abstractions for subnet selection and also support multiple applications simultaneously over the whole network. 39
Chapter 4. The Nano-CF Programming Framework 4.1 Motivation Many real-world deployments suffer from the problems of limited usability and low involvement of users, either because (a) the sensors are expensive and it may not be practical to deploy them with ideal or desired density, or (b) middleware support to allow seamless deployment of applications is inadequate. The former is addressed in [115] by sharing sensors among multiple deployments through human involvement and to address the latter, design requirements for a middleware to support concurrent applications are outlined in [116]. A typical use-case of supporting multiple applications simultaneously can be conceptualized on a university test-bed deployment like Sensor Andrew [29]. Sensor Andrew is a sense-actuate infrastructure deployed across the Carnegie Mellon University campus. The test-bed is used for inter-disciplinary research ranging from link-layer protocol development to design and testing of applications such as building-energy estimation and social-networking support systems like neighbor discovery. All the nodes in Sensor Andrew need to be programmed individually for supporting any new application. Furthermore, a user should contact a system administrator to re-program the network. As this test-bed is an interdisciplinary effort, researchers from different technical backgrounds use the infrastructure for their needs. To help better understand the goal of a middleware framework on a sensor deployment, the following simple example can be used. Consider a task that monitors temperature and humidity in various buildings regularly, and reports it to a civil engineering researcher interested in constructing an air-flow map of the building. In another task, a building manager might be interested in using the same infrastructure for a high-priority deadline-based fire alarm system. Users from such diverse technical backgrounds may benefit from a middleware layer that helps them program the network at an abstract higher level. A conventional macro-programming framework, however, may not allow more than one user to independently program the sensor network for handling these kinds of applications simultaneously. Furthermore, supporting multiple applications pose the additional challenge of coordinating tasks on every sensor node and scheduling radio transmissions. We propose a framework called Nano Coordination Framework (Nano-CF), to provide support to multiple programmers to write independent applications for a given sensing infrastructure. The framework seamlessly deploys those applications on the end nodes, and coordinates the packet delivery and data aggregation to reduce overall resource usage in the network. The proposed framework has a global view of various applications running on the network and 46
4.2. System Design their mutual interactions, it batches the sensing tasks and radio-usage together, with the help of Rate- Harmonized Scheduling (RHS) [41]. RHS proposes a scheduling scheme to maximize the sleep duration of a processor in case of periodic tasks. We adapt RHS to coordinate periodic radio usage tasks such that the packets from several tasks can be transmitted together and smaller packets can combined into larger ones . It is shown in the subsequent sections that significant savings in processor use and packet transmissions can be achieved through such a batching mechanism. In Nano-CF, multiple tasks are coordinated based on their timing parameters, within an allowable deviation as specified by the user. The major contributions of our proposed coordination framework are as follows: 1. It facilitates the use of a sensor-networking infrastructure by multiple programmers for multiple independent applications simultaneously. 2. It leverages the real-time and resource-centric features of an underlying sensor-network operating system for providing low-latency response. 3. It also improves the network lifetime by clustering processor usage and radio communication. 4.2 System Design Nano-CF (Nano Coordination Framework) is an architecture for macro-programming with coordinated operations in a WSN that encompasses multiple layers of a sensor networking system architecture, as shown in Figure 4.1. A main consideration behind the design of our framework is to support data-collection applications. Complex applications with actuation and distributed decisions can still be supported. However, the complexity of the resulting program can be quite high as the framework is not optimized for such programs. A user interacts only with the top layer of our system, which we call the Coordinated Programming Environment (CPE). For developing applications on the sensor network, a user only needs to write programs using the Nano-Coordination Language (Nano-CL) we developed for Nano-CF. The remaining functionality of providing the abstraction from the lower-layer networking and topology is handled by the CPE. The functions of the framework are divided into two main aspects: (i) to handle control information including the re-programming packets, and (ii) to collect data from sensors. All the three layers contribute towards the exchange of control information and data gathering. The CPE 47
Chapter 4. The Nano-CF Programming Framework Carnegie Mellon !"#$%&'()$*+( !"#$%"&' ()$)' !""#$%&'()$** +#",#'--%&,* )&.%#"&-)&(* ,+)+-.+/( %&(),#'(%"&* /'0)#* #1&(%-)* /'0)#* 0$/1"/*+/(233/+3"4$/( 5"/6+/( 7-68"4)9+/( 233/+3"4$/( &$*+(:#4+/8/+4+/( ;+#6$/(!$*+(<8+/"=#3(;>64+?( Figure 4.1: Layered architecture of Nano-CF provides a programming interface to allow the user to write, compile and send programs over the air. The CPE also returns the aggregated data corresponding to each the application independently to the user. The CPE consists of a parser and a dispatcher. The parser or compiler converts the functional definitions specified by the user to lower-level byte-codes and then the dispatcher sends them to the deployed sensor nodes. We assume that multiple WSNs are connected to each other via the Internet, where each WSN is composed of sensor nodes with at least one gateway node. The communication from the CPE to the end nodes is handled through the Integration Layer (IL). The Integration Layer encompasses all the nodes in the network and interfaces to the CPE through a gateway node. The gateway node implements a forwarder function to associate a specific task to a particular node and send corresponding programming packets to end nodes. An Aggregator module spreads over all three layers in Nano-CF to gather data from children nodes at a parent node in the 48
4.2. System Design subnets and finally present the result to the user interacting at the CPE layer. In addition to packet delivery and data aggregation, it is the function of the Integrator Layer to make sure that the timing properties of the applications specified by the user are delivered to the OS. THE Integration layer also handles the responsibility of batching tasks and packet transmissions together using RHS, details of which are provided in Section 4.4.3. The Runtime Environment of Nano-CF is implemented at each sensor node, above the operating system. At the lowest layer of this architecture, each node runs a byte-code interpreter to translate low-level instructions from the dispatcher to an executable form for the sensor node. Our architecture is highly portable because we only need to change the code interpreter to support different sensor network operating systems. Further implementation details along with the source code are provided at the project website [117]. 4.2.1 Nano-RK: a Resource-centric RTOS for Sensor Nodes Nano-RK [35] is a Real-Time Operating System (RTOS) designed and implemented to support resource reservations for wireless sensor nodes with a multi-hop packet transmission. By leveraging the timing characteristics of Nano-RK, such applications can be easily offered through Nano-CF. Virtual energy reservations introduced in Nano-RK also help Nano-CF to manage energy consumptions in each sensor node. By setting reservation values of (CPU, Network, Sensor) for runtime environment in a sensor node, we can enforce the expected power consumption. Since most other popular sensor node operating systems do not support multi-tasking by design, our current implementation is limited to Nano-RK. We aim to support more operating systems as future extensions of this framework. We used FireFly [1] sensor nodes with the Nano-RK operating system for our framework. Each node has an Atmel ATmega1281 processor and a Texas Instruments CC2420 Transceiver for IEEE 802.15.4 compliant wireless communication. In addition, a custom sensor expansion card can be connected to the FireFly main board. In particular, the sensor expansion card offers voltage sensing, dual axis acceleration, passive infrared motion, audio, temperature, and light. These diverse sensors supported by the FireFly platform suit the goal of Nano-CF to deploy multiple applicatons simultaneously. 49
Chapter 4. The Nano-CF Programming Framework 4.2.2 Routing and Link Layer Since Nano-CF requires byte-codes to be transferred to each sensor node in a multi-hop networking environment, the framework requires the support of underlying routing and link layer protocols. For the purpose of brevity, the details of the routing and MAC layer are not discussed in this chapter, and a brief background of related technologies is provided in Chapter 2. Our framework is flexible to operate over any transport layer as long as the gateway node is able to communicate with every node through unique addresses. Many sensor networks employ modified versions of routing protocols such as AODV [84] and DSR [118]. We used a DSR-based routing protocol with multicast for our evaluation. Below the routing layer, the link layer is crucial for data delivery. Time-Division Multiple Access-based RT-Link [82] and contention-based B-MAC [78] are two commonly used protocols with Nano-RK. In our implementation, we opted for B-MAC, but the operation of Nano-CF is independent of the lower-layer protocol used. Based on this fundamental architecture, we now describe the three main components of Nano-CF; Nano-CL in Section 4.3, the Integration Layer in Section 4.4, and the Runtime Layer in Section 4.5. 4.3 Nano-CL We designed an imperative-style language called Nano-CL (Nano Coordination Language) that provides a unified interface to users for writing sensor networking applications. The language has been designed to meet the following design goals: 1. The language should provide an abstraction from the lower-level details of the sensor networking OS and radio communication. 2. The language design should facilitate the extraction of timing and communication properties from user-written applications. 3. The syntax of the language should be simple and easy for non computer-scientists to understand and program. Each Nano-CL program is composed of two important sections: Job descriptor and Service descriptor, as shown in Figure 4.2. 50
4.3. Nano-CL JOB: <service1> <nodes> <rate> <agg_func> <service2> <nodes> <rate> <agg_func> ... END SERVICE: <service1> <return_type> /* instruction 1 */ /* instruction 2 */ ... END Figure 4.2: A figure showing the format of a Nano-CL program, consisting of a job descriptor and a service descriptor. 4.3.1 Service Descriptor In Nano-CL, the user writes a service which is functionally equivalent to a task that is to be executed on each node. Nano-CL consists of a set of primitives and programming constructs which provide sufficient capability for programming the sensor nodes, as well as, an abstraction from the lower-level implementation details of the operating system and radio communication. Each service descriptor specifies the functionality of one task. The syntax for a service descriptor is similar to ‘C’-like sequential programming, where the user can make use of pre-defined library functions to interact with the sensor hardware. The return value from the service corresponds to the data value that the user wishes to collect from the sensor nodes, and, unlike the usual practice, more than one data value can be returned. The framework converts the user program in service descriptor into byte-codes, which are then sent over the wireless network to be interpreted and executed at each node. 4.3.2 Job Descriptor A programmer can write multiple services and then each service can be mapped to a set of nodes in the job descriptor. The job descriptor section can have more than one service call where each call has the associated timing properties specified by the user. The timing properties include the periodic rate at which the service should repeat at each node and the maximum allowable deviation from the specified period. This deviation allows the framework to “batch” tasks together on sensor nodes, 51
Chapter 4. The Nano-CF Programming Framework as well as, schedule the transmissions together to reduce the overhead associated with switching on/off the radio and processor. This coordination of tasks and packet delivery across the network is explained in Section 4.4. A set of nodes given by <nodes> in the Job Descriptor section contains a list of all the nodes where the respective service should be executed. All the nodes in the network are assumed to have a unique identity, and are also mapped to a physical location in the network. The choice of having an explicit node-list to map the service is deliberate as Nano-CF can leverage the adaptive selection of nodes using some of the techniques already proposed in the literature such as [99, 119]. The routing layer can provide information about the network topology regularly, which can be used to dynamically select nodes in the job descriptor. The role of the <agg func> is explained in more detail in the next section. 4.3.3 Nano-CL Compiler The Nano-CL compiler (nclC) converts the source code consisting of services into byte-code streams. The compiler is designed with an aim to limit the byte-codes to a small subset of op-codes to allow the code-interpreter task on the end-node to have a small memory footprint. nclC adds metadata to the byte-code stream which helps the integration layer to extract information for batching the computation and radio usage on each node. It also specifies the timing properties for network-wide packet clustering. The metadata in the byte-code stream are generated from the information provided by the user in the rate section of the job descriptor, which consists of the period of the task and the allowable deviation from the period. The following are the timing parameters handled by the compiler: •Tsrv: Repeat rate of the current service. •Dev srv: Allowable deviation in the repeat rate of the service. The metadata are then sent along with the byte-code to individual nodes and are interpreted at the integration layer and the code interpreter. 52
4.4. Integration Layer 4.3.4 Example Nano-CL Program We provide a simple example of a Nano-CF program with two applications implemented using two services, shown in Figure 4.3. The aim of the first application is to find the number of occupied rooms in a building. We use a small network of four nodes at locations L1,L2,L3,L4 with one node in each room. We assume that each of the nodes has light, audio and temperature sensors, and are placed in such a way that the occupancy of the room can be determined by one node. Service occup monitor returns value 1if room is occupied or 0otherwise. Occupancy2, in this example, is determined by comparing an average of 10 samples of a weighted combination of light and audio levels in the room against a threshold. Various parameters in this example are chosen based on experimentation, and may not be applicable in all cases. In order to determine the number of occupied rooms from these locations of sensors, we use the SUM aggregation function. In second service temp collect, the user just wishes to collect readings of temperature every 50 secs. Please note that each of the services in this example could be created and programmed to a given sensor infrastructure by multiple users independently using Nano-CF. We have shown these services in a single program for ease of presentation. 4.4 Integration Layer The Integration Layer (IL) is responsible for byte-codes delivery, data aggregation, optimization of task execution and data transmission on the nodes in the network. This layer, shown in Figure 4.4, overlays across the gateway and the endnodes. 4.4.1 Byte-code Delivery The Forwarder module on the gateway node forwards the byte-codes generated by Nano-CL to the Receiver module on the end nodes. The primary features related to byte-code transfer are routing table management and fault-tolerant packet delivery. The routing table generated during the network initiation phase is used for communicating with the end nodes. Sequence numbers, end-to-end acknowledgements and packet retransmissions must 2We are providing a simple example for understanding purposes. Precision of monitoring is not a goal of this example. 53
Chapter 4. The Nano-CF Programming Framework JOB: occup_monitor <L1,L2,L3,L4> <20s,5s> SUM temp_collect <L1,L2,L3,L4> <50s,0s> NOAGG END SERVICE: occup_monitor uint8 int16 light_sense, audio_level; int32 sum; int8 cnt, thresh; sum = 0; cnt = 10; thresh=40; for(i=1:cnt) light_sense = gets(LIGHT); audio_level = gets(AUDIO); sum = sum + light_sense/100; sum = sum + audio_level/100; wait(1s); endfor if(sum/cnt > thresh) return 1; // Return 1, if room is occupied else return 0; endif END SERVICE: temp_collect uint16 return gets(TEMP); END Figure 4.3: An example Nano-CL program with two services 57 Figure 4.3: An example Nano-CL program with two services be used because one missing packet may cause the network to malfunction due to missing instructions. When end nodes try to reply to a request from their gateway, a broadcast storm problem may occur. In order to avoid this problem, packets are scheduled with an offset as explained in the next section. Each packet header contains additional fields like packet type, source address, destination address, application identifier, re-programming packet sequence number, packet identifier and total number of packets for this application. 54
4.4. Integration Layer 4.4.2 Data Aggregation The Integration Layer covers gateway node and end nodes, and links the programming environment to the runtime layer on end nodes. Nano-CF supports in-network data aggregation through the Aggregator module for reducing the packet overhead in the network. The aggregation scheme is defined by the user in the Job Descriptor of the program. In our current implementation, we support common commutative aggregation functions given in Table 4.1. The Aggregator handles different Table 4.1: Aggregation functions supported in Nano-CF Function Description MIN Minimum value of data MAX Maximum value of data SUM Sum of all data COUNT Number of replies received NOAGG Forward all data to CPE functionality at different levels. At the leaf nodes, the job of the aggregator is to send its own data. At at an intermediate level in the network, it should combine its data with that from all the child nodes according to the specified aggregate function. If the function is NOAGG, then the intermediate node concatenates data from each of the child nodes along with the node id and forwards it towards the gateway. The aggregator module at the gateway node communicates directly with the CPE and provides the aggregated data to the user. Whenever the Receiver module receives a new re-programming packet from the gateway node, it coordinates with the runtime layer to manage multiple applications from various users. 4.4.3 CPU/Data Coordination The IL provides task/network coordination for saving energy on each sensor node. Because most WSN applications are periodic, we utilize Rate-Harmonized Scheduling (RHS) [41]. 55
Chapter 4. The Nano-CF Programming Framework Table 4.2: Commonly used Byte-Codes in Nano-CF Instruction Type OpCode Declare/Assign: DECL, AEQ Arithmetic: ADD, SUB, MUL, DIV Comparison: GE, LE, EQ, GT, LT Constructs: IF, ELSE, FOR, GOTO I/O: SET, GET, TOGGLE, CLR Nano-RK: SEND, RECV, WAIT Macros: LABEL, SECTION, END 4.6 The sMapReduce Programming Abstraction In this section, we propose sMapReduce, a programming abstraction to divide the network-level user program into explicit sMap and Reduce functions. Most of the sensor networking applications can be visualised as accomplishing two important and largely disjoint functions, namely:i) Sense and compute, ii) Forward and Aggregate. Isolating these functions at the programming abstraction level helps a programmer not only to visualize the network operation with ease, but also to implement complex application logic. The sMap operation maps the application behavior to the structure of the network. Hence, we call our approach sMapReduce, which stands for structure-Map & Reduce.Structure means the network topology and the configuration of nodes, including the hardware and software capabilities. By application behavior, we mean the expected functionality of the structure of the network of sensor nodes. The Reduce function handles the responsibility of data aggregation in the network-tree topology. In this regard, several abstraction concepts from the field of distributed computer systems can be adapted to sensor networks. Sensor networking applications are typically less data-intensive but data are highly correlated to physical location as nodes are deployed to sense the environment. In addition, gathering data efficiently from the nodes in a multihop network requires aggressive packet scheduling and aggregation to reduce the radio and computation resource-utilization. Our proposed programming pattern is inspired from the MapReduce framework [121], a popular data-processing approach in distributed systems. MapReduce framework requires a programmer to divide the processing job into Map and Reduce functions. Map takes a key-value pair as input and converts it to 62
4.6. The sMapReduce Programming Abstraction 1 smap( service name , list of nodes , period ){ 2for each node in list of nodes 3 temp value = gets (TEMP) ; 4 smap emit ( temp value , node id ) ; 5 end (a) sMap Function 1 reduce ( data , list of nodes ) { 2for each node in INNER. list of nodes 3 sum += data . temp value ; / /AGGREGATION 4 end 5return sum; 6} (b) Reduce Function Figure 4.8: A simple example for collecting sum of temperatures from a wireless sensor network. another intermediate key-value pair; Reduce does the job of combining this intermediate output from Map. Researchers have adapted MapReduce for processing of data on large sensor networks [122] with the premise that nodes carry huge amount of data and parallel computations are required in some applications. We take this concept a step further by mapping behavior to sensor nodes based on their logical and physical topology. The reduce concept is employed to implement aggregation logic over the network tree. 4.6.1 The sMapReduce Programming Pattern In this section, we describe our proposed sMapReduce programming pattern for developing applications on sensor networks. As has been emphasized earlier, the bifurcated operation of sensor networks into behavior mapping and data-aggregation motivates a corresponding split in network-level programs. The user programs each application using two key functions: sMap and Reduce. The main objective of sMap is to associate sensing and decision-making jobs to the sensor nodes and the Reduce function handles collection of data through the network-tree while allowing the user to implement complex aggregation logic. sMapReduce is a higher-level programming pattern that maintains its expressiveness though disjoint sMap and Reduce functions. A simplified example of an sMap function is shown in Figure 4.8a. The sMap function takes three 63
Chapter 4. The Nano-CF Programming Framework input arguments: service_name is the identifier of the application to be executed on the sensor nodes, list of nodes is a handler for data structure(or a database) containing topology and tree information of the nodes, and period is the period in ms at which the application repeats itself. The information about the sensor nodes, their hardware and location is compiled and stored in a data-structure during deployment. Most sensor network deployments are done manually, hence the mapping of physical location to a node id can be obtained in this phase. Once such mapping is available, a programmer can refer to a node through its unique id, or through the more abstract concept of physical location, logical location in the tree or even filtered based on sensor capability. The sensor capability can be specified by the availability of certain type of sensor, computation power or available battery capacity. Even in the case of dynamic topologies, the underlying routing and communication infrastructure can share the responsibility of providing frequently updated logical node location and topology information to the programming abstraction. The functionality of nodes is decided in an sMap function. The user can make use of predefined library functions and programming constructs to create programs for the network. Some of the commonly used programming features have been listed in Table 4.3. Table 4.4 provides a list of operators to select a subset of nodes from list_of_nodes. In the example shown in Figure 4.8, we present a simple sMap application for collecting temperature data from all nodes in the network. The code for this application consists of a for loop to iterate through the list of nodes, an instruction using get() to read the temperature reading and then an smap_emit() to send the temperature reading along with the node id towards the gateway. The Reduce section of the program is used to specify the aggregation scheme. A separate dedicated section in the program to perform aggregation provides more freedom and flexibility to implement data collection algorithms. The user can assign aggregation responsibilities to different nodes in the network tree. It makes it easier to overlay complex aggregation algorithms over the tree through higher-level abstractions for node addressing. This two-fold advantage is made possible by separating the sensing operation from the data-aggregation in sMap and Reduce sections. Figure 4.8b shows an example of a reduce function for calculating the sum of temperature readings obtained in the sMap section in Figure 4.8a. In this example, the INNER operator is used to select non-leaf nodes and the sum of the input temperature data is calculated over all nodes. The sum of these temperature readings can be used to calculate a more useful parameter such as the average temperature at the 64
4.6. The sMapReduce Programming Abstraction Table 4.3: List of the sMapReduce programming constructs Construct Details list_of_nodes Data structure containing the list of nodes and their properties smap_emit() Data to be returned by each node get() Function to read sensor values into integers, takes sensor name as argument set() Function to set a GPIO Pin clear() Clear a GPIO Pin toggle() Toggle a GPIO Pin Table 4.4: List of operators for selecting participating nodes from among the list of nodes Operators Details LEAF. Nodes on the periphery of the network INNER. All nodes except the leaf nodes HOP(k). All nodes at kth hop from the gateway HAS(t). All nodes that have a ttype sensor BATT(c). All nodes having remaining battery capacity of atleast c CONN(n). Nodes having at least nneighbors gateway node. It is trivial to compute commutative operations like sum, maximum, minimum and count. Moreover, as a user can access the nodes according to their physical location or logical location in the network tree, more complex aggregations schemes can be implemented as well. 4.6.2 A Target Tracking Example Target tracking is a common application in sensor networks and requires considerable coordination between nodes. We provide an example implementation using the signal strength of beacons from a target node in order to demonstrate the advantage of using sMapReduce. The application logic is split into sMap and Reduce functions as shown in Figure 4.10. The sMap function reads the Received Signal Strength Indicator (RSSI) values from received packets as shown in line 3 in Figure 4.10a. The Reduce function in Figure 4.10b triangulates the location of the target when an intermediate node receives information packets from at least three children nodes. 65
Chapter 4. The Nano-CF Programming Framework In the sMap function, each node generates four values: RSSI, corresponding time stamp, location of target and its own ID, as shown in line 5 in Figure 4.10a. The Reduce function receives these values from sMap, and evaluates an aggregation at all intermediate nodes. As shown in the example topology in Figure 4.9, only node 6is able to collect three values required for triangulation of the target node Ttracked by nodes 1,2and 3. The Reduce function in the example implements the majority of the application logic because only an intermediate node can process the RSSI information to estimate the location of the target. The reduce function also ascertains the temporal correlation of RSSI values from different nodes by checking whether all the time stamps lie within a window of size win (line 6, Figure 4.10b). It is evident from this example that sMapReduce performs aggregation close to the leaf nodes, reducing the communication and computation overhead near the gateway node. The triangulate() function in line 8 calculates the location of a target node based on the RSSI values and the coordinates of infrastructure nodes. Approaches like TinyDB do not capture sensing or topological modalities, as the aggregation is handled by an automated query planner. The design of application logic might be simpler in TinyDB in many cases but sMapReduce allows a programmer more control with an implicit understanding of physical and logical location of nodes. More complex schemes like Regiment do not isolate the functionality from aggregation explicitly, which can complicate the application logic with sensing job being undesirably coupled to various points in the program. 4.6.3 Mapping Applications for Mobile Nodes The sociometric badge [123] is an example sensor network application that targets assisted-living scenarios. The infrastructure for such an application is expensive to maintain once the nodes have been distributed and deployed. Adding additional features is likely to be impossible, and the lack of resources on specific nodes restricts the services that they can offer. The presence of mobile nodes also adds additional complexity with respect to node re-programming and data aggregation. The proposed programming pattern, sMapReduce, provides a flexible and extensible mechanism to develop such systems, which could consist of both mobile and static sensor nodes. In order to support such systems, sMapReduce introduces two new aspects: (i) multi-level sMap and Reduce function support, and (ii) periodic map execution. This enables system designers to use sMapReduce on sensor network systems with mobile nodes. Figure 4.11a shows an example system, where a mobile node called Fire- 66
4.6. The sMapReduce Programming Abstraction !" #" $" %" &" '" (" )" *" + !"#$%"&' ()*$' +),-.$' /"01$#' Figure 4.9: An example topology to demonstrate location tracking of a target node Fly badge [124] is used to build the above-mentioned assisted living infrastructure. The FireFly badge could be hosting two location-based applications: (i) an emergency alarm application that needs to be loaded when the user is in a bathroom, and (ii) a schedule reminder application that needs to be loaded when the user is in a living room. The smap location function is executed periodically, and it tracks the location of the FireFly badge so that smap location can map the corresponding application to the badge. Then, smap service, the second-level map function, will map schedule reminder to the badge if the user is in the living room and emergency alarm if the user is in the bathroom. Therefore, depending on the user location, a different application can be dynamically mapped on to the mobile node, and this enables programming of context-sensitive sMap or Reduce operations. This example thus illustrates a simple scenario where the multi-level mapping and periodic map execution features of sMapReduce can enable its use in networks with mobile nodes, where platforms such as [31, 32, 33] cannot be easily applied. 67
Chapter 4. The Nano-CF Programming Framework 1 smap( target track , list of nodes , period ){ 2for each node in list of nodes 3 rssi v = get ( RSSI ) ; 4 ts = get ( time ) ; 5 smap emit ( rssi v , ts , node id , loc ) ; 6 end (a) sMap Function 1 reduce ( data , list of nodes ) { 2for each node in INNER. list of nodes 3if ( data . loc != NULL) 4return data . loc ; 5else 6if (max( ts )−min( ts )<=win 7 && size ( data . rssi v ) >= 3) 8 triangulate ( rssi v , loc ) ; 9else 10 return data ; 11 end 12 end 13 end 14 } (b) Reduce Function Figure 4.10: A location tracking example using RSSI values of packets received by infrastructure nodes from a mobile target. 4.6.4 Features The design of the sMapReduce programming pattern is based on the principle that a typical sensor network operation consists of two relatively disjoint functions. One associates a behavior to sensor nodes and another executes data aggregation over the distributed network. Hence, dividing the user program in explicit sMap and Reduce sections is a natural fit to sensor network operation. We provide below some features of the pattern to emphasize on the design decisions behind the sMapReduce. Two-fold operation A typical sensor network operation consists of programming of the nodes and collection of data. These two are handled independently at different layers in the network. Further details of this operation are provided in Section 4.7. Data correlation A sensor network is a distributed system where data of interest comes from the physical environment itself. Therefore, any computation on data should be conducted in the 68
4.7. System Design 1 target service = smap location ( FireFly Badge , list of nodes , period ) ; 2 data = smap service ( target service .name, target service . nodes , target service . period ) ; 3 result = reduce ( data , list of nodes ) ; (a) An example code for supporting mobile nodes 1 smap location ( service , list of nodes , period ) { 2for each node in INNER. list of nodes 3if ( node . location == bathroom ) 4 smap emit ( emergency alarm ) ; 5else if (node . location == livingroom ) 6 smap emit ( schedule reminder ) ; 7 end 8 end 9} (b) Implementation of the first-level sMap function Figure 4.11: An example of mobile node support close neighborhood of the sensor node. Programmer Support The explicit division of programs into sMap and Reduce sections allows the programmers to easily isolate the key functions, thus helping in easy inference and debugging of applications. Balanced abstraction and control sMapReduce provides easy-to-use libraries and abstractions to deploy large-scale applications in addition to the ability to address individual nodes for finegrained control to the user. Expressiveness sMapReduce is a pattern derived from the operation of a sensor network, and it allows the programmer to conveniently map the behavior of sensing and aggregation to the network structure. The programmer can leverage subtle optimizations without much complexity in the application logic. 4.7 System Design As previously stated, a typical operation of a sensor network involves two major components: one handles the programming of and coordination among nodes, and another governs aggregation of data 69
Chapter 4. The Nano-CF Programming Framework !"#$"%&&'($)*+,-"%./#() 0#12)3(-2"4"2-2") 52(,#")65) !"#$%#& '($)"*+,%#& -.#/"#0%#& 1%+%(2%#& 344#%4"*.#& 344#%4"*.#& 0667839*:;8) !76<7*==39<)) ;9>3769=;9:) 39:;<7*:369) ?*@;7) 7A9:3=;) Figure 4.12: sMapReduce system architecture with three major layers to support a network-level programming abstraction over the multi-hop network tree. We can conceptualize this two-fold operation as two independent planes that we call the sMap plane and the Reduce plane. Based on this concept, sMapReduce facilitates a programmer to distribute functionality in two separate sections. 4.7.1 sMap Plane In the sMap operation of the system, the primary function is to assign specific behavior to each of the nodes in the network. Behavior in this case means all tasks executing on the node, along with communication handling and participating in data forwarding and aggregation. The layered structure along with sMap and Reduce operations is shown in Figure 4.13. The top-layer of this architecture is the programming abstraction for the user to create network-level programs in sMap and Reduce sections. The user-written program is compiled and converted into byte-codes to be executed on individual nodes. Byte-code execution implements the node behavior with the support from the sensor operating system. Byte-code is sent via the wireless network to each of the nodes, which is handled by a data-handler in the Integration Layer. The data-handler connects all sections of sensor networking 70
4.7. System Design !"#$"%&&'($)*+,-"%./#() 0#12)3(-2"4"2-2") 52(,#")65) !"#$%#& '($)"*+,%#& -.#/"#0%#& 1%+%(2%#& 344#%4"*.#& 344#%4"*.#& ,7%4) !8%(2) 5%,"2(.#& 6"))(74& 921:.2) !8%(2) 344#%4"8.7& Figure 4.13: A figure showing the operation of sMap and Reduce planes. sMap operation involves top-down mapping of behavior to each node from gateway to leaf nodes, and Reduce handles data aggregation from leaf-nodes upwards infrastructure spread over various layers, from the user-end PC at the top to the gateway node and intermediate nodes in the middle and to leaf nodes at the bottom. Once the byte-codes are delivered to each node according to their function, a code-interpreter converts them to sensor networking OS instructions. The byte-codes contain both the program to be executed and the aggregation scheme to be followed at each intermediate node. The main job of the sMap plane is to provide network abstraction and assign jobs to nodes while maintaining coordination among multiple applications and network hops. 4.7.2 Reduce Operation Once the nodes receive the byte-code specifying their functionality/behavior, the nodes start the execution of the new application. The role of each node in the Reduce plane is also included in the bytecode where the intermediate nodes in the network tree help in aggregation of data. The aggregation of data is specified by the user in the Reduce section of the program. The role of aggregation can 71
Chapter 5. Redundancy Elimination across Applications consume about 2−3orders of magnitude more processor cycles than a simple memory-based instruction. With the increase in the number of applications deployed on a sensor network, the overhead because of sampling the sensors can also increase dramatically. Hence, by sharing the sensing requests among the applications, a significant percentage of resource usage and energy can be saved on a sensor node. We propose a solution able to achieve such energy savings through a compile-time approach. The challenges involved in such an approach are discussed next. Computer science researchers have long focused on designing compiler optimizations to remove redundancies and dead-code in a program. Several simple optimizations are standard features in most modern compilers; complex features can also be enabled for specific optimizations based on overall program logic [125]. In general-purpose computing systems (e.g. desktop computers or datacenters), independent applications may have similar logic but it is very unlikely that they share the same data as well. This makes inter-application redundancy elimination a less-explored research area, as the possibility of energy savings is quite low. For instance, two independent users may want to use a distributed system to compute Fast Fourier Transform (FFT) over large datasets. Even though the computation module of FFT is the same for both the users, it is highly unlikely that the dataset will be the same as well. Hence, the provisions of sharing the same result among the two users may not be beneficial in terms of energy savings. In sensor networks, however, the data of interest typically is the sampled values of the physical quantities, and it is significantly more likely that different applications may require sampling of the same sensors. We show using our proposed approach that sharing those samples can achieve considerable energy savings. As most sensing applications are periodic in nature and have low duty-cycles, eliminating redundant sections in case of mismatching periods can be difficult, and may not provide significant gains if elimination is carried out using simple temporal overlap detection. Secondly, the applications can sample the sensors multiple times at different intervals and in different order. Compiler support is a practical and effective technique for identifying such requests and optimizing them for finding better overlap. Finally, redundancy elimination at each node at run-time can add significant complexity to the scheduler on the sensor node. The scheduler in this case will have to pre-profile the execution of the program to identify the overlapping sections. We propose a novel solution to the problem of finding overlapping sensing requests issued by network-wide applications created by independent users. We model each application as a linear se- 78
5.1. Overview of the Approach quence of executable instructions, and find a merged sequence of multiple applications through the use of well-known string-matching algorithms. In particular, we use the Longest Common Subsequence (LCS)[38] and the Shortest Common Super-sequence (SCS)[39] techniques. Our proposed solution creates a monolithic task-block resulting from the optimized merging of user applications with embedded scheduling information. This scheme is particularly advantageous in cases where the relative order of sensing requests is important, and simply caching the values may not help. One such case can be envisaged in an application where multiple sensors are sampled at different intervals but in a specific order to infer patterns of target behavior as may be the case in assisted living scenarios, or sensor-fusion based localization. We show that our approach can help in achieving about 60% average energy savings in processor usage as compared to the execution of several applications without eliminating such redundancies. The organization of the rest of this chapter is as follows. First, we provide an overview of our approach in Section 5.1. Section 5.2 and Section 5.3 provide the details of the modeling of applications and the proposed redundancy elimination approach, respectively. We finally evaluate our approach in Section 5.4. 5.1 Overview of the Approach We assume that the users develop network-level sensing applications using a higher-level programming framework. The application code written by the users can either be at an abstract network-level using a macro-programming language like Regiment [31] or it can use node-specific virtual-machines (for example Mat` e [32]). In both these cases, the programming framework creates node-level intermediate code based on the application logic specified by the user. Our approach is based on a machine-language like intermediate code, generally referred to as bytecode. The architecture of such a complete system is shown in Figure 5.1, where the user applications are converted into bytecode by a parser, such that each output instruction is either an indivisible subexpression or a special function for accessing the hardware (including sensing, GPIO access or packet transmission). Bytecode corresponding to all the applications are converted to a monolithic code by the Redundancy Eliminator with Implicit Scheduler (REIS) module. This monolithic code, which we call REIS-bytecode and ρ-code in short, is a merged sequence of all the applications with the redundancies eliminated according to 79
Chapter 5. Redundancy Elimination across Applications !"#$%&'(%)"' !"#$%&'(%)"' ! " # $ % & ' ( ) !"#$% &''()*+,-."% *+&$"&' /01#*-2#% ,")-#)+#./'01234' 5267'83912.26' !.7")-12#:' ;2&"1"$$' ("65%&<' &''()*+,-.% 31-$+4#% ,08!' =/6".%)"' !"#$%&'(%)"' ,%->#:' =/6".%)"' 8#6"&9&"6"&' 5#16-$7% 8+.+4#$% Figure 5.1: Overview of the approach for redundancy elimination the temporal overlap of the sensing requests. REIS-bytecode is then sent over the wireless network to each sensor node where the applications are to be executed. A bytecode interpreter at the sensor node executes the received REIS-bytecode. Our approach assumes that a data link-layer and a suitable routing layer are already implemented on the sensor node and our solution is transparent to it as long as end-to-end packet delivery is supported. A network manager module handles the responsibility of dynamically updating the routing tables, and maintaining the network topology information. As users issue applications to the system independently, our approach requires an application storage database to store the bytecode and merge them using the REIS module whenever a new application is submitted. The semantics of each user application is embedded within the REIS-bytecode such that the maximum sharing of sensing requests and radio transmissions is obtained. Bytecode from different applications share non-overlapping variable and address space, which removes any need for context switching, and the interleaving of bytecode provides an implicit schedule of execution. The motivation behind the sharing of sensing requests can be justified based on the comparison of the time taken for reading a sensor sample into memory with a simple memory-based instruction. Figure 5.2 shows an oscilloscope capture of this comparison on a WSN platform with an Atmel AT- 80
5.1. Overview of the Approach !"#$%&'& !"#$%&(& Figure 5.2: An oscilloscope screenshot showing the comparison of the time taken for reading a sensor sample against a memory-based operation MEGA1281 processor. This comparison is obtained by toggling a GPIO pin just before and after the execution of a sensor sampling instruction (shown by Trace 1) and a memory-based loading of a 16- bit value into a register (Trace 2). The former takes about 500 microseconds but the latter instruction takes only 10 microseconds. Please note that this time comparison also includes the time taken for toggling the I/O pins. As the ATMEGA1281 (8MHz) processor on the sensor node has on-chip memory, a load instruction takes a maximum of 3 cycles that correspond to 375 nanoseconds. A majority of the time consumed in the case of Trace 2 is because of the pin toggling. Hence, a sensor sampling instruction consumes up to (500−10)×10−6 375×10−9= 1306 times more power. This factor, which we refer to as φ(time-factor), is specific to the platform and the operating system. However, the order of magnitude of φcan be assumed to be similar across most sensor network systems. In addition, radios on newer System-on-Chip (SoC) solutions like the ATMEL ATmega 128RFA1 [40] support 2 Mbps data rate, compared to 250 Kbps from the commonly used CC2420 [53] radio for about 20% less power consumption. This implies that the power per packet can be reduced by a factor of 8, bringing the power consumption of the radio closer to that of the processor. Hence, optimizations at the processor level are bound to play a significant role in reducing total energy consumption, 81
Chapter 5. Redundancy Elimination across Applications in contrast to the majority of research efforts focusing mainly on energy savings at the radio. 5.2 Application Modeling Our proposed optimizations are aimed at applications whose main goal is to sample sensors, process the sensor data for more meaningful results, and then transmit the results towards a gateway node through the network tree. Each bytecode instruction contains a list of hex opcodes, and is of the form: <TYPE OP1 OP2 OP3 ...>, where TYPE defines the kind of operation, and operand OP<K> can have specific usage based on the bytecode. For the sake of clarity, example formats of some relevant bytecodes are provided in Table 5.1. The specific implementation can vary based on the design of the Parser and the Bytecode Interpreter. Table 5.1: Example bytecode structure for some relevant subexpression instructions Operation Opcode Details Sense S t VAR Sample sensor tand copy the value in VAR Assign AEQ VAR1 VAR2 Assign VAR1 = VAR2 Transmit T DEST VAL1 VAL2 Transmit VAL1 &VAL2 to DEST node Compute C VAR1 VAR2 VAR3 VAR1 := VAR2 ‘C’ VAR3 5.2.1 Conversion to a sequence of nodes Most sensor networking applications are of the form: Sense-Compute-Transmit (SCT), as the users are typically interested in sampling one or more sensors, processing the data from the sensors and collecting the processed results at a gateway node. Such applications can be modeled as a string of nodes where each node represents a sub-expression in the bytecode,β, as shown in Figure 5.3. Strepresents a sensing request (or a sampling request) for sensor type t, where tcan be either be temperature (T), light (L), accelerometer (X, Y, Z) or any other sensor available on board. Cdenotes nodes with al- 82
5.2. Application Modeling !"# !$# %# %# !&# %# %# "# !"# %# "# '(()*+,-./#0# '(()*+,-./#1# "234# Figure 5.3: An example showing a linearized execution sequence for one instance of two applications. Application 1 samples three different sensors, and Application 2 samples the temperature and transmits its scaled-down value. gebraic computation. As most sensor nodes typically have one kind of radio for communication, we use Tto denote nodes corresponding to packet transfer via the radio. This conversion of bytecode sub-expressions to nodes is captured by the function create node() in Algorithm 1. As algebraic computations are generally data-dependent, finding the overlap across Cnodes is considerably less plausible. Moreover, there are no significant energy savings by eliminating such overlap, as these instructions typically consume a small (about 1 to 2) number of machine cycles, particularly on a sensor network platform having a RISC processor and on-chip memory. Hence Stand T-type nodes participate in finding the overlap across applications, and are called Anchor Nodes. Conditional statements in an application may not allow it to be converted into a linear string. We present the techniques for modeling applications having at least one anchor node inside the conditional statements in the next subsection. The conditional statements without an anchor node can be trivially mapped to a Ctype node. 5.2.2 Modeling Conditional Statements As it cannot be known at compile-time which execution path can be taken in case of a conditional statement, it is not possible to create a ρ-code (REIS-bytecode) from the input bytecodes based on a linear application model as described in Section 5.2.1. We propose an algorithm to create a functionally equivalent code with a maximum possible number of sequential nodes, such that the conditional statements in the output bytecode sequence βηare purely computational. Algorithm 1 provides a solution where the anchor nodes (sensing/sampling requests) are moved to before the beginning of 83
Chapter 5. Redundancy Elimination across Applications the outermost conditional statement in case of nested if-loops. An assign instruction is inserted in the place of the original instruction, which loads the value returned by the sensing request into the variable originally designed to read the output of sensing instruction, as shown in lines 19-21 in the algorithm. An example scenario is shown in Figure 5.4, where the original sampling request inside an if-condition is moved to before the outermost if-statement and the sampled value is stored in a temporary variable var1 temp. The original variable, var1, is assigned the value of var1 temp at its original location in the bytecode. if (condition)! ...! var1 = sense(TEMP)! ...! end! var1_temp = sense(TEMP) ! if (condition)! ... ! var1 = var1_temp! ...! end! Figure 5.4: An example showing the modeling of an if-condition for redundancy elimination across applications. Please note that the sensing requests are data-independent instructions; moving them to a previous point in the code does impact the application logic. Also, moving a sensing request earlier does not impact the sampled value, because there will only be a very small change in the exact sampling instant of the order of microseconds. Moreover, determining and enforcing an exact sampling instant is not always feasible in most sensor network operating systems. Hence, the sensed value is not compromised in terms of its temporal correctness. 5.2.3 Merging Packet Transmissions It can be claimed that, for better power savings, the transmit nodes Tshould also be moved towards the end of the bytecode sequence to obtain better overlap of radio usage across applications. We, however, do not take such an approach in this chapter, since a solution is proposed in Chapter 7 to harmonize packet transmissions from different applications. Instead of transmitting whenever the applications request, the packets are queued in a local buffer and are transmitted at instants that provide maximum overlap of radio transmissions. As the radio is a shared resource among applica- 84
5.2. Application Modeling Algorithm 1: convert app(Ai): convert an application to bytecode βη 1 Algorithm 1: convert app(Ai): convert an application to bytecode ⌘ Input :Ai: A user created application Output:(⌘,Nan): Bytecode node sequence, Number of moved anchor nodes 1Parse Aito bytecode using the parser 2INITIALIZATIONS: 3⌘:=;;if index := ;;node := ; 4if depth := 0;Nan =0; 5foreach sub-expression ⌘2do 6i=IndexOf(⌘) 7if ⌘is an if-clause then 8if depth ++; 9if index ·append(i); 10 ⌘·append(⌘); 11 else if ⌘=Sthen 12 if if index·isEmpty() then 13 index =i; 14 else 15 index =if index(i); 16 Nan ++; 17 end 18 node := create node(type(⌘),var); 19 ⌘·insert(index, node); // move Snode before the beginning of outermost if-condition 20 node := create node(assign,var,op2(node)); 21 ⌘·append(node); 22 else if ⌘is an endif-clause then 23 if depth ; 24 if index ·pop back(); 25 ⌘·append(⌘); 26 else 27 ⌘·append(⌘); // Non anchor nodes remain at the same relative location 28 end 29 end transmitted at instants that provide maximum overlap of radio-transmissions. As radio is a shared resource among applications, such a queue based mechanism can help in achieving what is aimed by our proposed approach. Many other solutions (such as [111]) have been proposed to optimize the network-wide scheduling of packets. For brevity purposes, we 68 tions, such a queue-based mechanism can help in achieving what is aimed by our proposed approach. Many other solutions (such as [126]) have also been proposed to optimize the network-wide schedul- 85
Chapter 5. Redundancy Elimination across Applications !"# !$# %# %# !&# %# %# "# !"# %# "# "'()# &# &#&# &#&# *++,-./012#3# *++,-./012#4# Figure 5.5: Application 2 modified to be aligned with Application 1 for sharing sensing requests and packet transmission (based on the example in Figure 5.3) ing of packets. 5.3 Redundancy Elimination with Implicit Scheduling 5.3.1 String-Matching Algorithms Once an application is modeled as a sequence of nodes as described in the previous section, the problem of finding overlapping sections among two or more applications can be reduced to that of finding a common subsequence between a pair of applications. The Longest Common Subsequence (LCS) is a technique commonly used to find the overlap between a pair of strings of symbols such that the relative order of common symbols is the same in both the input strings. LCS provides one such common sequence having the longest possible length. Consider the two following string sequences: SENSOR and NETWORK. The longest common subsequences are {N,O,R},{E,O,R}but the Longest Common Sub-String (LCSS) would just be {O,R}. A longest common substring is always a subset of the longest common subsequence, but the opposite may not be true. There are some commonly available solutions [38] that are guaranteed to return alongest ordered subsequence between a set of input strings. LCSS can help in finding redundant anchor nodes that appear consecutively in the input sequences. As an improvement over LCSS, LCS finds a subsequence with maximum overlap such that the relative order of nodes is not sacrificed. One or more of the input applications may be ‘stretched’ at various points, as illustrated in Figure 5.5 after applying LCS to the applications shown in Figure 5.3. An optimal merger of input sequences can be obtained by using an approach related to LCS 86
5.3. Redundancy Elimination with Implicit Scheduling called Shortest Common Super-sequence (SCS)[39]. Definition 1. Given input sequences Xand Y, the shortest common super-sequence, Z=SCS(X, Y ), is the shortest sequence such that both Xand Yare subsequences of Z. In the case of two input sequences, it is trivial to find the SCS if the LCS is known. For more than two sequences, finding the SCS is not a direct application of the LCS solution. Algorithm 2: REIS(Γ): Generate a monolithic ρ-code with implicit scheduling from an input set of applications Input :Γ: a set of napplications < A1, A2,...An>each with period Pifor ith application Output:ρ-code: a monolithic bytecode sequence // From Equation 5.1 1PH:= LCM(P1, P2. . . Pn) 2INITIALIZE: 3for i= 1 : ndo 4βnew,i := ∅; 5end 6foreach application Ai∈Γdo 7(βη,i, Nan,i) = convert app(Ai); 8for j= 1 : PH Pido // create new strings 9βnew,i := concatenate(βnew,i, βη,i); 10 end 11 end 12 ρ-code =SCS(βnew,1, βnew,2,...βnew,n); One important aspect of applications designed to operate on sensor networks is periodicity. Applications are typically designed as tasks that repeat periodically with low duty-cycles. Different applications deployed on a sensor network may have unequal periods. This adds further complexity to the redundancy detection and elimination across applications. Let us assume that an application Aihas a period Pi; the harmonizing period PHis given by: PH=LCM(P1, P2,...Pn)(5.1) where LCM stands for the Least Common Multiple of the input values. 87
Chapter 5. Redundancy Elimination across Applications 1 2 3 4 5 6 7 8 9 10 10 20 30 40 50 60 70 80 90 100 Number of sensors per node Normalized energy savings (%) 3 applications 5 applications Figure 5.10: Percentage energy reduced with an increase in the number of sensors. Overall, the achievable energy savings from the proposed approach is highly case-specific, but there is a high potential of energy savings if there are more applications or the utilization is high because of sensing-intensive workload. 5.5 Limitations It can be argued that our application model is simplistic. It is, however, practical and it increasingly covers more and more scenarios of applications of large-scale sensor network deployments. Indeed, it does not support variable for-loops, and memory requirements can get prohibitive if loop unrolling is implemented. We leave an assessment of these issues to future work. Our approach is a compile-time technique, and therefore all applications are affected if one application changes or is added. On the other hand, a dynamic run-time approach can add significant overhead to the bytecode interpreter on the sensor node. In order for a run-time approach to efficiently eliminate redundancies across applications, pre-profiling of those may be required that can result in significant memory and processor overhead. Moreover, a compile-time approach is still beneficial if the rate of re-programming of the network is low. 94
5.6. Summary and Discussion 5.6 Summary and Discussion In this chapter, we have proposed and discussed a novel compiler-assisted scheduling approach that is able to identify and eliminate redundancies across applications in wireless sensor network infrastructures. Our approach models applications as linear sequences of executable instructions and we propose suitable algorithms for constructing such a model. We then show how it is possible to exploit and adapt well-known string-matching algorithms such as the Longest Common Subsequence (LCS) and the Shortest Common Super-sequence (SCS) techniques to produce an optimal merged sequence of the multiple applications with implicit scheduling. As modern radio designs support higher data-rates for the same amount of power, the optimizations on processor power consumption become more relevant for energy-saving and increasing the lifetimes of sensor networks. On the other hand, with the increase in the number of applications deployed on a sensor network, the overhead because of sampling the sensors can increase dramatically. However, by sharing sensing requests among applications, a significant percentage of resource usage and energy can be saved on a sensor node. We demonstrate how our approach of using high-level optimization leads to significant network-wide resource savings, importantly energy. Our approach outperforms many other known techniques in the case of sensor node platforms supporting multiple sensors of multiple types. Our approach is highly predictable and its runtime is fairly simple: execution of bytecode with implicit scheduling. We show, based on experiments, that our proposed compile-time redundancy elimination approach can provide on an average about 60% energy savings on the processor with several simultaneous applications. In the next chapter, we propose the design of a hierarchical system, where a monolithic REIS- Bytecode can be assigned to one of the tasks running on the operating system, rather than being the only executing block. Such a system can be modeled as an application of the classical bin-packing problem, where tasks can be clubbed together based on properties such as priority and memory requirements, providing scope for Quality-of-Service support in addition to resource optimizations. 95
Chapter 5. Redundancy Elimination across Applications 96
Chapter 6 Hierarchical Assignment In the previous chapter, we extended the advantages of a holistic over-the-air programming scheme by designing a novel compiler-assisted scheduling approach (called REIS) able to identify and eliminate redundancies across applications. In this chapter, we propose a hierarchical assignment scheme where the applications may be merged into multiple intermediate blocks, rather than one large monolithic block. Our evaluation shows that significant energy savings can be obtained by removing redundancies in sensor sampling, while meeting the resource constraints on the sensor nodes. However, it might become impractical to combine all the applications into one large monolithicblock, as the size of the block might grow to be too large. As a further optimization, we present a hierarchical approach, where the tasks are merged into more than one intermediate task-block such that certain constraints regarding timeliness and memory usage are satisfied. The task-blocks are then executed as independent tasks on the sensor nodes. We show in this chapter that this hierarchical scheduling problem can be modeled in a way similar to that of a classical bin-packing problem. We provide certain approximations such that the problem can be reduced to that of quadratic programming and, hence, solvable with a reasonable time complexity. If the relative sequence of the sensor sampling requests is not important, then a caching-based solution can also be a possibility, where the sensor readings are cached in memory along with a timestamp. Whenever an application requests a new sample, the cached value is checked for its freshness, and if it newer than a threshold, the value is used as it is. Otherwise, a new sensor sample is taken and
Chapter 6. Hierarchical Assignment 1typedef struct { 2int16tvalue; 3timetcurrtime; 4}sensor t; 5sensor t sensor; 6//wrapper function definition 7sensor tgetsensor val(SENSOR){ 8timetct; 9ct=getcurr time() ; 10 if (ctsensor. curr time >THRESH) { 11 // collect new sensor sample using 12 // the original function 13 sensor . value = get sensor(SENSOR) ; 14 sensor . curr time = get curr time () ; 15 } 16 else { 17 //return the cached value 18 return sensor; 19 } 20 return sensor; 21 }; Figure 6.1: Pseudo-code showing the wrapper function to collect sensor readings from a cache-based solution 81 Figure 6.1: Pseudo-code showing the wrapper function to collect sensor readings from a cachebased solution provided to the application. Such a solution, devised using a wrapper function shown in Figure 6.1, is disadvantageous in a few major ways compared to our compile-time approach. Firstly, caching may not be practical in applications with fast-sampling rate. Secondly, it may not be directly applied in the cases where the relative order of samples from different sensors is important. As an example, an application may want to know when the light turned is on in a room by reading a light sensor, and then compare it with the reading from a motion sensor. Cached values in such a case may jeopardize the application semantics. If caching still needs to be used, the application behavior should be modified to be able to compare the time-stamps corresponding to different sensor samples requiring additional state maintenance. Thirdly, caching requires comparing of time-stamps which are typically 32-bit values; through simple experiments we found that it can take approximately 120µs to return the cached value (using the else path in Figure 6.1). This is significantly more computationally expensive as compared to reading a 16-bit value stored in memory with the Nano-RK [35] operating system running on a Firefly [1] sensor node that takes about 10µs, as explained earlier and shown in Figure 5.2. 98
6.1. Hierarchical Assignment 6.1 Hierarchical Assignment In the approach described so far, all the user applications are merged into one monolithic task-block, which may have some disadvantages listed below. •Different periods of the deployed applications may result in a large hyper-period, causing the size of the task-block to be prohibitively large. This not only increases the memory footprint, but also increases the number of packets required to transmit merged applications to the end-nodes. •The applications may lose some timeliness because different parts of the applications may be executed with varying delays in the process of finding a better overlap. •Some tasks may suffer significant delays in capturing the sensor sample and then using it, which may negatively impact application semantics. •Data from some critical tasks (e.g., monitoring fire) may not be delivered with the required responsiveness. •Including less sensing-intensive applications in the task-block may not conducive to energy savings. We now present a hierarchical approach where we merge the applications into one or more intermediate task blocks instead of a large monolithic block. Let us consider a sensor node Operating System (OS) with support for multiple concurrent periodic tasks. The problem of executing the userapplications in such an OS can be represented as a hierarchical assignment one as shown in Figure 6.2. The goal is to strategically combine user-application tasks into multiple task-blocks such that several application requirements can be met. For example, merging applications with differing periods can cause the task-block to have a large memory footprint, and it may be beneficial to create more than one task-blocks such that tasks with similar periods are together. Similarly, creating task blocks from input tasks which share the same sensors may help in saving more energy. 6.1.1 Problem formulation In order to find the assignment of tasks to intermediate blocks, we consider only the string model of the tasks. Other properties of the tasks, such as the semantics and timing behavior, are maintained 99
Chapter 6. Hierarchical Assignment User% Applica,on%1%% User% Applica,on%2%% User% Applica,on%3%% User% Applica,on%n%% Alloca&on(Engine( ( ( ( Sensor(Node(Opera&ng(System( Wireless(Network( Task;Block(1( Task;Block(2( Task;Block(m( Rx(( Task( Tx(( Task( Task(2(Task(1( Task(m( Figure 6.2: An architecture diagram showing the process of hierarchical assignment scheme for redundancy elimination. as described earlier in Section 5.2. Let us assume that we have a set τof ntasks deployed on the sensor nodes, and the corresponding bytecode string set is B. The ith string is represented by βi, where i= 1,2, . . . , n. The tasks can be mapped to mtask-blocks denoted by ρj, where 1≤j≤mand m≤n. The task-block is denoted by the symbol ρbecause each task-block corresponds to a merged sequence of application strings, which we termed as REIS-bytecode or ρ-code as in Section 5.3. The challenge is to find an optimal mapping of nbytecode strings to mblocks such that the total energy consumption of all the applications is minimized within certain constraints. We model the problem as one of quadratic integer programming, which is an NP-hard problem with a solution space growing exponentially with respect to n. We also derive suitable approximations that provide a solution with reasonable time-complexity, but at the expense of exact optimality. The total energy consumed by the system can be considered as the sum of the energy consumption of every application as follows: Etotal =X ∀i Eβi(6.1) Also, if the tasks are combined into task blocks, the total energy consumed is the sum of the energy 100
6.1. Hierarchical Assignment of all blocks. Therefore, E0 total =X ∀j Eρj(6.2) The energy consumption of the jth block can be obtained by subtracting the energy corresponding to the total degree of overlap across the tasks in the block from the total energy consumed by the tasks in the block, as follows. Eρj =X ∀i∈ρj Eβi−∆j·es(6.3) where, ∆jis the total degree of overlap in the jth task-block, and esis the energy consumption of each sensing request. It results from (6.1), (6.2) and (6.3) that the energy savings after mapping tasks to task blocks can be estimated as: Es=Etotal −E0 total =X ∀j ∆j·es(6.4) From (6.4) it is clear that, to maximize the energy savings, the total degree of overlap across all taskblocks should be maximum. The estimation of ∆jis challenging as it involves finding the Shortest- Common Supersequence (SCS) for application strings with respect to each block. The degree of overlap for a given set B⊆Bof bytecode strings is given as: ∆j=X ∀βi∈B (PH Pi )Li−Lρ(6.5) where, PHis the hyper-period of all the ntasks as defined in (5.1). Piis the period of the ithtask. Li denotes the length of βiin number of bytecode instructions or nodes (Figure 5.3), and Lρis the length of the task-block obtained by finding the SCS of the input tasks strings. The challenge, however, lies in calculating the SCS for all combinations of βi’s so that the optimum combinations can be chosen for mblocks where Pm j=1 ∆jcan be maximized. There can be a prohibitively large number of such combinations that can make the optimization problem intractable. The optimization problem can consist of terms of arbitrary polynomial degree up to n. The problem will then require the partitioning of set Binto mnumber of disjoint subsets, and thus, there can be an exponential number of such partitions that are typically calculated by the means of Bell number and Bell polynomials [127]. In order to be able to find an optimum assignment of tasks to task-blocks, the SCS’s of all possible partitions may 101
Chapter 6. Hierarchical Assignment need to be found along with solving the optimization problem. Hence, a major challenge lies in decoupling the problem from the calculation of SCS, so that it can be solved as a typical optimization problem with an objective function to be maximized while meeting some constraints. Let us assume that the jth block has happlications and λk,l denotes the longest-common subsequence of the kth and the lth string in the set. The following theorem helps to approximate the optimization problem to one of Quadratic Integer Programming (QIP) with linear constraints. Such problems can still be NP-hard, but commercial solvers [128, 129] are available that and be used to solve them. Subsequently, we further approximate the model to a Quadratic Continuous Program that may be solved in polynomial time, but with loss of optimality. Theorem 1. The total degree of overlap over a set Sof bytecode strings is less than or equal to the sum of the lengths of the Longest Common Subsequences (LCS’s) of all the pairs in this set. ∆j≤1 2X ∀k,l∈B λk,l s.t. k, l ≤n&k6=l(6.6) The equation is multiplied by a factor of half because λk,l =λl,k. Proof. According to its definition, the Shortest Common Supersequence (SCS) of a set Sof kstrings contains all the elements of all the input strings but without any redundant elements. The SCS ρof the strings in Sis the shortest possible string such that all the strings in the set are subsequences of ρ. The shortest possible string can be found by removing redundant elements across all pairs of strings in the set S. The number of removed elements is equal to the sum of the lengths of the LCS’s of all the pairs. However, in this process, an element that participates in all possible pairs of LCS’s of p(2< p < k) strings, gets removed p 2times rather than its actual redundancy degree of p−1. As p 2is greater than p−1, the total degree of overlap is less than the sum of the lengths of the LCS’s. The equality prevails when no identical elements occur in more than two LCS’s. As evident from the proof above, the exact value of the total degree of overlap is dependent on the elements of the constituent strings. Hence, it is not possible to isolate the problem formulation from finding the SCS, if an exact solution is to be found. The sum of the lengths of the LCS’s of all the pairs 102
6.1. Hierarchical Assignment provides an upper-bound on the degree of overlap across all strings, and is used as an approximation to strategically combine tasks into task-blocks. Based on Theorem 1, we can now re-formulate the objective function so that the problem space can be reduced. In order to formulate the optimization problem, we make use of inclusion variables denoted by Xj i, where Xj i= 1if βiis assigned to block j 0otherwise (6.7) Each task can only be assigned to one task-block to avoid repetition, which implies the following: for each i, X ∀j Xj i= 1 (6.8) To find an optimal assignment of tasks to task-blocks, we quantify the degree of overlap by summing the pairwise degree of overlap multiplied by the inclusion variables, and the constraint in (6.8) accomplishes exclusion by making sure that each task is assigned to only one block. The goal of the optimization problem now is to find the values of the inclusion variables such that the total degree of overlap is maximized. Please note that the degree of overlap across two bytecode strings is the same as the LCS of the two, as described in Section 5.3. Hence, we can say: X ∀pairs∈B λeach pair =X ∀a,b∈{1,2,...n},a6=b Xj aXj bδa,b (6.9) From Theorem 1, the objective function for the jth task-block can now be written in an expanded form as: ∆j≤Xj 1Xj 2δ1,2+Xj 1Xj 3δ1,3+···+Xn 1Xj nδ1,n+ Xj 2Xj 3δ2,3+···+Xj 2Xj nδ2,n +···+ Xj n−1Xj nδ(n−1),n (6.10) We can now create a general form so that the total degree of overlap Dtotal across all task-blocks can be maximized. Let Drepresent the n×nmatrix where the (k, l)th element is δk,l. The degree of 103
Chapter 6. Hierarchical Assignment 110
Chapter 7 Network-Harmonized Scheduling In the previous chapters, we proposed optimizations for reducing the resource consumption at the processor and sensor level by eliminating the redundancies across applications. However, there is still scope for optimizing the network behavior when multiple applications are executed on sensor nodes. It is often the case that applications release packets independently in the network, which can lead to excess energy consumption due to factors like increase in the number of packets, more frequent radio-switching and extra contention at the Medium Access Control (MAC) layer. The energy consumed in transmitting a packet from a source node to a destination node depends on many aspects, and with common MAC approaches, a packet may undergo contention at several points in a multi-hop network. This jeopardizes the deterministic behavior of the network and makes it very difficult to provide any timing guarantees. In this work, we present the Network-Harmonized Scheduling (NHS) approach, in which radio transmissions from multiple applications are coordinated across a multi-hop network by harmonizing them around periodic boundaries, while obviating the need for explicit MAC and routing layers. NHS is a simple and effective approach that is inspired by Rate-Harmonized Scheduling (RHS) [41] and applied to the context of multi-hop networking. By using NHS, it is possible to provide real-time performance guarantees in a multihop wireless network without requiring any central coordination. Even if applications release one or more packets in a periodic manner, the overall packet transmission by a sensor node may no longer be periodic because of the mismatching periods of different
Chapter 7. Network-Harmonized Scheduling applications. In such a case, the total number of packets released by a sensor node grows proportionally with respect to the number of deployed applications. All the packets may suffer contention at different hops in the network if the underlying MAC layer is based on a carrier-sense mechanism. Therefore, multiple applications releasing packets independently may increase the overall resource consumption in the network. Moreover, the latency suffered by packets in a dense multi-hop network may become prohibitively large and non-deterministic. To overcome these issues, NHS aligns packet releases from different applications around periodic boundaries at each node, and leverages this periodic behavior to harmonize the transmissions at the network level. NHS includes a light-weight protocol that groups periodic batched transmissions from different devices, such that the nodes can turn on their radios when other devices transmit. We first describe the protocol assuming that all nodes lie in a single broadcast domain. We further develop the protocol to support multi-hop scenarios, where we harmonize packet transmissions in a periodic manner without any global state maintenance. One of the major advantages of our protocol is that it includes an implicit link-layer mechanism, and, from its multi-hop operation, it can be inferred that dedicated route maintenance is also not required. Moreover, the protocol provides deterministic bounds on the end-to-end latency for packet delivery, and design parameters can be chosen such that the packet deadlines can be met for real-time applications. This characteristic emphasizes the usefulness of NHS in sensing and actuation networks with closed-loop operation, such as Cyber-Physical Systems [133]. We also analyze the performance of NHS with respect to parameters such as end-to-end latency, maximum utilization of the channel and average power consumption. The implementation of NHS is simple (∼400 lines of code), and does not require the modification of application semantics. Applications only need to declare their period of operation and the maximum number of packets they may transmit in every round. Each node only maintains information about its neighbors, but can still achieve a performance (in radio duty-cycle) similar to that of Time-Division Multiple Access (TDMA). NHS requires only a few cycles to converge to a stable schedule, and does not need additional information exchange if the network remains static. Our approach can also optionally provide a contention slot for supporting mobile and intermittently connected devices. The key features of our Network-Harmonized Scheduling approach can be summarized as follows: •A harmonizing task is designed for sensor nodes that batches together the transmissions from 112
7.1. Model and Assumptions multiple applications by ensuring that packets are released into the network only at periodic boundaries. •A protocol is proposed that coordinates packet transmissions in a network around periodic boundaries. For multi-hop networks, this protocol works in a distributed manner and pipelines the transmissions from successive hops to make sure that no collisions occur at any node. •We implemented NHS1on the Contiki operating system, and we show through experiments that the protocol is suitable for real-time applications by providing deterministic bounds on parameters such as the end-to-end latency, channel utilization and radio duty-cycle. The remainder of this chapter is organized as follows. We describe the state-of-the-art in the next section, and contrast NHS with other studies that also aim at optimizing the network operation. In Section 7.1, we outline the assumptions made in our approach and propose the model of the applications and the sensor network. The process of batching the packet transmissions using RHS (which inspired NHS) is explained in Section 7.2. The protocol to harmonize data from multiple nodes in a single broadcast domain is proposed in Section 7.3, followed by the description of the NHS approach for generic multi-hop networks in Section 7.4. In Section 7.5, we discuss various design parameters, Section 7.6 provides the details about our implementation of NHS on Contiki and Section 7.7 contains the results from experimental evaluation. In Section 7.8, we provide a brief discussion of potential applications of NHS, its limitations and different possible ways to address them. We finally summarize the NHS protocol in Section 7.9. 7.1 Model and Assumptions In this work, we assume that several network-wide applications execute concurrently on a sensor network, and each application has a corresponding node-level task that releases periodic jobs on each sensor node. The set of all the tasks on a sensor node is represented by Γ. We assume that there are ntasks in Γ, and the ith task is denoted by τi, where i∈ {1,2, ..., n}. The tasks execute on top of the Network-Harmonized Scheduling layer as shown in Figure 7.1. Every task releases an infinite number of jobs with a period of Ti. Without any loss of generality, we sort the tasks in an 1Our implementation of the Network-Harmonized Scheduling protocol can be obtained at [134] 113
Chapter 7. Network-Harmonized Scheduling Hardware Drivers Sensor Operating System Harmonizing Task (τn)$ NHS Layer τ1$ τ2$ τn$ τsync$ Task$Layer$τ3$ Figure 7.1: Layered architecture of Network-Harmonized Scheduling (NHS) protocol non-descending order of their periods, and then assign serial indices to the tasks. Hence, it follows that T1≤T2≤. . . Tn. Every job may sample the sensors, process the data from sensors or incoming packets, and release one or more packets towards a destination node. Assuming that the maximum number of packets a job of the ith task can transmit is pi, the time consumed by the packets for transmission is wi=pi·δ, where δis the duration corresponding to one packet. As an example, the value of δfor IEEE 802.15.4 packets of size 128 bytes transmitted at 256 Kbps is 4ms. One of the tasks deployed on a sensor node can act as a simple clock synchronization service, τsync, that executes periodically. The management and exchange of MAC-level time-stamps and correction of clock-drift is the responsibility of this clock synchronization task which sits above the Network- Harmonized Scheduling protocol layer. As we will see in the next section, the harmonizing period (period of network operation) is chosen to be at least as small as the period of the most frequent task, allowing the synchronization task to comfortably operate at the desired frequency. It will be evident from the description of the protocol that each node only maintains a schedule according to its immediate neighbors and NHS only requires that a child node be synchronized with its parent. The nodes are assumed to have unique id’s, and the number of nodes in the network is assumed to be bounded by N, and a multi-hop operation may be required to communicate from a root node to another node in the network, or vice-versa. Let hmax be the maximum number of hops required for connecting a root to all other nodes in the network, and Qdenotes the maximum degree of connectivity in the network. 114
7.2. Rate-Harmonized Scheduling for Packets 7.2 Rate-Harmonized Scheduling for Packets Rate-harmonized scheduling (RHS) [41] is a policy that optimizes the execution of tasks on a uniprocessor system such that the job executions of all the tasks are aligned near the period boundaries of the task with the shortest period (the most frequent task). RHS saves power by removing inefficient switching in processor states, namely active, idle, and sleep, based on the observation that the power consumption in the sleep state is orders of magnitude lower than that in the idle state, but going to and coming out of the sleep state takes longer time. RHS makes sure that the task executions are harmonized and aligned in time, and the processor can optimally go to deep-sleep states more often and for longer time-spans. We adapt RHS in this work to align packet transmissions by different periodic applications on a sensor node, such that the overhead of radio switching can be avoided, and the packets are released into the network in a periodic manner. With multiple tasks releasing packets at every Titime units, the transmission pattern can be irregular as shown with an example in Figure 7.2a. The packets in the example are transmitted using the well-known Rate-Monotonic Scheduling (RMS) approach. On the other hand, the packets from various tasks are batched together with a harmonizing period TH=T1as shown in Figure 7.2b. RHS is implemented using a simple queueing mechanism, where every job of all the tasks submits packets to a harmonizing task, τH, instead of directly copying them into the radio-buffer. τHthen transmits all the packets in its queue with a period of operation equal to a harmonizing period,TH. As the packets from a node are transmitted in a contiguous manner (back-to-back) as a batch, the number of radio switchings is reduced significantly. An important distinction in the scheduling of packets is that preemptions are not possible once the packets transmission begins, whereas, most task-scheduling approaches on a processor, however, allow preemption. Harmonizing using the above mechanism converts intermittent packet transmissions from a sensor node into periodic batch-releases, and this periodicity is a fundamental buildingblock for further optimizations as described in the subsequent sections. 115
Chapter 7. Network-Harmonized Scheduling τ1" τ2" τ3" Radio" Tx" Radio Sleep!Transmit! (a) Packet transmission from different tasks, if scheduled using Rate-Monotonic Scheduling. The task with a shorter period has higher priority. The number of independent packet transmissions over a time-window is the sum of number of packets from each task. t=0!t=10!t=20!T=30!t=40! τ1" τ2" τ3" τH" Radio Sleep! Transmit! (b) The transmission schedule after harmonizing the transmissions. The harmonizing task (with a period of TH=T1= 10 time-units) makes sure that the packets are dispatched in batches, never more often than the harmonizing period. Figure 7.2: A task set with three tasks τ1, τ2, τ3, with periods of 10, 15 and 26 time-units respectively, scheduled by Rate-Monotonic Scheduling and Rate-Harmonized Scheduling. Block arrows show the time-instants when the packets are released by different jobs of the tasks. 7.3 Single Broadcast Domain Once the packet transmissions from multiple tasks are batched around the harmonizing period, we can design a distributed online protocol to align packets transmitted by multiple nodes in a single broadcast domain. Let us assume that the nodes have unique id’s and, for simplicity, the root (or a cluster head) is already known among the nodes. The goal is to create a scheme where the transmissions from all the nodes can be gathered at the root in a periodically regular manner. The protocol works as follows. A simplified operation with a root node and 4 nodes with id’s a, b, c and dis shown in Figure 7.3. •Initially, all the nodes turn on their radios and listen to any incoming packets. The root transmits 116
7.3. Single Broadcast Domain a b c d t=0!t=TH!t=2TH! a b cd Figure 7.3: Aligning packet transmissions in a broadcast domain around periodic boundaries. a b c d a b c d t=0!t=TH!t=2TH! Figure 7.4: Aligning packet transmissions before the scheduled transmission by the root node, optimized for collection of data from all the nodes. a beacon to initiate the protocol, with its node id and the harmonizing period. •All the nodes listen to this beacon, and take note of the root id and the transmission period. The nodes locally create a schedule by assigning transmission slots as a monotonic function of node id, such that each transmission slot is unique to each node. This implies that the nodes with lower id transmit earlier, and those with higher id transmit later. •Until the next period boundary, all the nodes listen to the medium after transmitting a chosen slot. As the node id’s are assumed to be unique, it is guaranteed that there is no collision in any slot in the network. •All the nodes listen to the medium during this period and they learn about the other nodes in the broadcast domain, and their respective slots. It is possible that there may be several empty slots in the schedule, and the nodes can then independently compress the schedule by removing the empty slots in the next cycle as shown in the second cycle of Figure 7.3 and Figure 7.4. •From the next round onwards, the packets are transmitted in a compressed schedule such that the root only wakes up periodically for a duration equal to the total time required by all the slots. All the other nodes only wake up close to their slot in the schedule to transmit their data. In this example, the protocol is designed for nodes to choose slots after the scheduled transmission by the root node in the next cycle. However, the protocol can also be modified such that the nodes 117
Chapter 7. Network-Harmonized Scheduling transmit before the next transmission by the root as shown in Figure 7.4. This is more beneficial in datacollection-oriented applications, because the root can receive the data and then react to the data in the same cycle. The difference in these two approaches is more pronounced in the multi-hop scenario (discussed in the next section), where the first approach is better suited for flooding and the second for many-to-one communications. This protocol helps to remove the overhead of contention and random back-off as in the case of carrier-sense MAC protocols, and achieves TDMA-like timing efficiency without the need to maintain a global schedule. The width of each slot, denoted by σ, has to be large enough to accommodate batched packets, but short enough so that a Harmonizing Period can accommodate packets from all the nodes; that is: δ n X i=1 pi≤σ≤TH N(7.1) 7.3.1 Addressing the Hidden-Terminal Problem There can be cases of collisions in a multihop scenario due to hidden-terminal problems, because some nodes may occupy the same slot as a hidden terminal when the schedule is being compressed. This is avoided by ensuring that the root (or a parent) sends a message containing the list of successful receptions during the bootstrapping phase. Hence, every node becomes aware of other hidden terminals, and avoids choosing overlapping slots. If a node receives a packet from more than one parent node in the bootstrapping phase, then it chooses a parent which is closest to it, by considering the signal strength of the received packets. In this way, the network topology is generated by setting up parent-child links. If the topology changes, and a node does not receive a packet from its parent for a preset number of cycles, it choses a different parent within its neighborhood. By design, NHS is more suitable and reliable for static and nomadic sensor deployments than mobile and intermittent networks. 7.4 Harmonization in a Multi-Hop Network We now extend the above approach to a multi-hop scenario where all the nodes have to send their data to a sink in the network. The protocol described in the previous section is easily applicable to 118
7.4. Harmonization in a Multi-Hop Network r a b c d e f gh i j k l mn o Figure 7.5: An example multi-hop network, with 15 nodes, and a root-node (r). Solid lines depict bi-directional wireless links. multi-hop topologies with minor modifications, so that the possibility of collisions and packet-drops due to the hidden-terminal problem can be eliminated. The root initiates the protocol by broadcasting atrigger beacon, which is received by the neighbors of the root. Similar to the case of a single broadcast domain, the children nodes listen to the beacon, then choose slots as a function of their id’s and then compress the schedule. The nodes at the second hop-level should not transmit until the schedule has been compressed, because the nodes at this level cannot listen to all the transmissions at the next level closer to the root. Each node in the network has information only about its 1-hop neighbors and its peers (siblings with the same parent). The main goal of this protocol is to enable scheduled transmissions in a distributed manner, without requiring global knowledge of the network-topology and without explicit time-synchronization. The working principle behind the protocol is to ensure more than 2-hop distance in simultaneous transmissions in the network. Assigning slots to transmissions in a TDMA-based network is typi- 119