SlideShare a Scribd company logo
TinyOS programming 1st Edition Philip Levis pdf
download
https://ebookgate.com/product/tinyos-programming-1st-edition-
philip-levis/
Get Instant Ebook Downloads – Browse at https://ebookgate.com
Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...
Sheep 1st Edition Philip Armstrong
https://ebookgate.com/product/sheep-1st-edition-philip-armstrong/
The Collected Poems of Philip Lamantia First Edition
Philip Lamantia
https://ebookgate.com/product/the-collected-poems-of-philip-
lamantia-first-edition-philip-lamantia/
Dear Zoe 1st Edition Edition Philip Beard
https://ebookgate.com/product/dear-zoe-1st-edition-edition-
philip-beard/
Philip Kaufman 1st Edition Edition Annette Insdorf
https://ebookgate.com/product/philip-kaufman-1st-edition-edition-
annette-insdorf/
Alec Wilder 1st Edition Edition Philip Lambert
https://ebookgate.com/product/alec-wilder-1st-edition-edition-
philip-lambert/
Valode Pistre Architects 1st Edition Philip Jodidio
https://ebookgate.com/product/valode-pistre-architects-1st-
edition-philip-jodidio/
Computer Programming 1st Edition E. Balagurusamy
https://ebookgate.com/product/computer-programming-1st-edition-e-
balagurusamy/
Carbon Programming 1st Edition Kevin Bricknell
https://ebookgate.com/product/carbon-programming-1st-edition-
kevin-bricknell/
Programming Clojure 1st Edition Stuart Halloway
https://ebookgate.com/product/programming-clojure-1st-edition-
stuart-halloway/
TinyOS programming 1st Edition Philip Levis
This page intentionally left blank
TinyOS Programming
Do you need to know how to write systems, services, and applications using the TinyOS
operating system? Learn how to write nesC code and efficient applications with this
indispensable guide to TinyOS programming.
Detailed examples show you how to write TinyOS code in full, from basic applications
right up to new low-level systems and high-performance applications. Two leading
figures in the development of TinyOS also explain the reasons behind many of the
design decisions made and explain for the first time how nesC relates to and differs
from other C dialects. Handy features such as a library of software design patterns,
programming hints and tips, end-of-chapter exercises, and an appendix summarizing
the basic application-level TinyOS APIs make this the ultimate guide to TinyOS for
embedded systems programmers, developers, designers, and graduate students.
Philip Levis is Assistant Professor of Computer Science and Electrical Engineering at
Stanford University. A Fellow of the Microsoft Research Faculty, he is also Chair of the
TinyOS Core Working Group and a Member of the TinyOS Network Protocol (net2),
Simulation (sim), and Documentation (doc) Working Groups.
David Gay joined Intel Research in Berkeley in 2001, where he has been a designer
and the principal implementer of the nesC language, the C dialect used to implement
the TinyOS sensor network operating system, and its applications. He has a diploma in
Computer Science from the Swiss Federal Institute of Technology in Lausanne and a
Ph.D. from the University of California, Berkeley.
TinyOS programming 1st Edition Philip Levis
TinyOS Programming
PHILIP LEVIS
Stanford University
and
DAVID GAY
Intel Research
CAMBRIDGE UNIVERSITY PRESS
Cambridge, New York, Melbourne, Madrid, Cape Town, Singapore, São Paulo
Cambridge University Press
The Edinburgh Building, Cambridge CB2 8RU, UK
First published in print format
ISBN-13 978-0-521-89606-1
ISBN-13 978-0-511-50730-4
© Cambridge University Press 2009
2009
Information on this title: www.cambridge.org/9780521896061
This publication is in copyright. Subject to statutory exception and to the
provision of relevant collective licensing agreements, no reproduction of any part
may take place without the written permission of Cambridge University Press.
Cambridge University Press has no responsibility for the persistence or accuracy
of urls for external or third-party internet websites referred to in this publication,
and does not guarantee that any content on such websites is, or will remain,
accurate or appropriate.
Published in the United States of America by Cambridge University Press, New York
www.cambridge.org
eBook (EBL)
paperback
Contents
List of Code examples page xi
Preface xvii
Acknowledgements xix
Programming hints, condensed xxi
Part I TinyOS and nesC 1
1 Introduction 3
1.1 Networked, embedded sensors 3
1.1.1 Anatomy of a sensor node (mote) 4
1.2 TinyOS 5
1.2.1 What TinyOS provides 6
1.3 Example application 7
1.4 Compiling and installing applications 8
1.5 The rest of this book 8
2 Names and program structure 10
2.1 Hello World! 10
2.2 Essential differences: components, interfaces, and wiring 13
2.3 Wiring and callbacks 15
2.4 Summary 16
Part II Basic programming 19
3 Components and interfaces 21
3.1 Component signatures 21
3.1.1 Visualizing components 22
3.1.2 The “as” keyword and clustering interfaces 23
3.1.3 Clustering interfaces 24
3.2 Interfaces 24
3.2.1 Generic interfaces 27
3.2.2 Bidirectional interfaces 28
vi Contents
3.3 Component implementations 29
3.3.1 Modules 30
3.3.2 A basic configuration 31
3.3.3 Module variables 32
3.3.4 Generic components 33
3.4 Split-phase interfaces 34
3.4.1 Read 36
3.4.2 Send 36
3.5 Module memory allocation, avoiding recursion, and other details 36
3.5.1 Memory ownership and split-phase calls 38
3.5.2 Constants and saving memory 41
3.5.3 Platform-independent types 42
3.5.4 Global names 44
3.5.5 nesC and the C preprocessor 46
3.5.6 C libraries 47
3.6 Exercises 48
4 Configurations and wiring 49
4.1 Configurations 50
4.1.1 The −> and <− operators 51
4.1.2 The = operator 52
4.1.3 Namespace management 53
4.1.4 Wiring rules 54
4.1.5 Wiring shortcuts 56
4.2 Building abstractions 57
4.2.1 Component naming 58
4.2.2 Component initialization 59
4.3 Component layering 60
4.3.1 Extensibility 61
4.3.2 Hardware specificity 61
4.4 Multiple wirings 63
4.4.1 Fan-in and fan-out 64
4.4.2 Uses of multiple wiring 65
4.4.3 Combine functions 66
4.5 Generics versus singletons 68
4.5.1 Generic components, revisited 68
4.5.2 Singleton components, revisited 70
4.6 Exercises 70
5 Execution model 71
5.1 Overview 71
5.2 Tasks 72
5.2.1 Task timing 74
Contents vii
5.2.2 Timing and event handlers 75
5.3 Tasks and split-phase calls 75
5.3.1 Hardware versus software 75
5.3.2 Tasks and call loops 76
5.4 Exercises 78
6 Applications 79
6.1 The basics: timing, LEDs, and booting 79
6.1.1 Deadline-based timing 81
6.1.2 Wiring AntiTheftC 83
6.2 Sensing 83
6.2.1 Simple sampling 84
6.2.2 Sensor components 85
6.2.3 Sensor values, calibration 86
6.2.4 Stream sampling 87
6.3 Single-hop networking 89
6.3.1 Sending packets 90
6.3.2 Receiving packets 93
6.3.3 Selecting a communication stack 94
6.4 Multi-hop networking: collection, dissemination, and base stations 95
6.4.1 Collection 96
6.4.2 Dissemination 97
6.4.3 Wiring collection and dissemination 97
6.4.4 Base station for collection and dissemination 98
6.5 Storage 101
6.5.1 Volumes 102
6.5.2 Configuration data 103
6.5.3 Block and Log storage 105
6.6 Exercises 111
7 Mote-PC communication 112
7.1 Basics 112
7.1.1 Serial communication stack 113
7.2 Using mig 114
7.2.1 Sending and receiving mig-generated packets 116
7.3 Using ncg 118
7.4 Packet sources 119
7.5 Example: simple reliable transmission 120
7.5.1 Reliable transmission protocol 121
7.5.2 Reliable transmission in Java 121
7.5.3 Reimplementing TestSerial 125
7.6 Exercises 125
viii Contents
Part III Advanced programming 127
8 Advanced components 129
8.1 Generic components review 129
8.2 Writing generic modules 131
8.2.1 Type arguments 132
8.2.2 Abstract data types as generics 133
8.2.3 ADTs in TinyOS 1.x 134
8.3 Parameterized interfaces 135
8.3.1 Parameterized interfaces and configurations 137
8.3.2 Parameterized interfaces and modules 139
8.3.3 Defaults 141
8.4 Attributes 142
8.5 Exercises 144
9 Advanced wiring 145
9.1 unique() and uniqueCount() 145
9.1.1 unique 146
9.1.2 uniqueCount 147
9.1.3 Example: HilTimerMilliC and VirtualizeTimerC 147
9.2 Generic configurations 150
9.2.1 TimerMilliC 150
9.2.2 CC2420SpiC 152
9.2.3 AMSenderC 156
9.2.4 BlockStorageC 160
9.3 Reusable component libraries 162
9.4 Exercises 165
10 Design patterns 166
10.1 Behavioral: Dispatcher 166
10.2 Structural: Service Instance 170
10.3 Namespace: Keyspace 174
10.4 Namespace: Keymap 177
10.5 Structural: Placeholder 180
10.6 Structural: Facade 183
10.7 Behavioral: Decorator 186
10.8 Behavioral: Adapter 189
11 Concurrency 192
11.1 Asynchronous code 192
11.1.1 The async keyword 192
11.1.2 The cost of async 193
11.1.3 Atomic statements and the atomic keyword 195
Contents ix
11.1.4 Managing state transitions 197
11.1.5 Example: CC2420ControlP 197
11.1.6 Tasks, revisited 199
11.2 Power locks 200
11.2.1 Example lock need: link-layer acknowledgements 200
11.2.2 Split-phase locks 201
11.2.3 Lock internals 202
11.2.4 Energy management 203
11.2.5 Hardware configuration 204
11.2.6 Example: MSP430 USART 204
11.2.7 Power lock library 205
11.3 Exercises 205
12 Device drivers and the hardware abstraction architecture (HAA) 206
12.1 Portability and the hardware abstraction architecture 206
12.1.1 Examples 208
12.1.2 Portability 210
12.2 Device drivers 210
12.2.1 Access control 211
12.2.2 Access control examples 212
12.2.3 Power management 215
12.2.4 Microcontroller power management 218
12.3 Fitting in to the HAA 219
13 Advanced application: SoundLocalizer 221
13.1 SoundLocalizer design 221
13.1.1 Time synchronization 222
13.1.2 Implementing SoundLocalizer in TinyOS 223
13.2 SynchronizerC 225
13.3 DetectorC 230
13.4 MicrophoneC 233
13.5 Wrap-up 237
Part IV Appendix and references 239
A TinyOS APIs 241
A.1 Booting 241
A.2 Communication 241
A.2.1 Single-hop 242
A.2.2 Multi-hop collection 243
A.2.3 Multi-hop dissemination 244
A.2.4 Binary reprogramming 245
A.3 Time 245
A.4 Sensing 245
x Contents
A.5 Storage 246
A.6 Data structures 247
A.6.1 BitVectorC 247
A.6.2 QueueC 247
A.6.3 BigQueueC 248
A.6.4 PoolC 248
A.6.5 StateC 249
A.7 Utilities 249
A.7.1 Random numbers 249
A.7.2 Leds 249
A.7.3 Cyclic redundancy checks 250
A.7.4 Printf 250
A.8 Low power 251
References 252
Index 254
Code examples
2.1 Powerup in C page 10
2.2 PowerupC module in nesC 11
2.3 Simple nesC interfaces 11
2.4 PowerupAppC configuration in nesC 12
2.5 Powerup with blinking LED in C 15
2.6 Powerup with blinking LED in nesC (slightly simplified) 15
2.7 Powerup with blinking LED configuration (slightly simplified) 16
3.1 The signature and implementation blocks 21
3.2 Signatures of PowerupC and LedsC 22
3.3 MainC’s signature 22
3.4 The LedsP module 23
3.5 PowerupC and an alternative signature 24
3.6 Interface declarations for Leds and Boot 25
3.7 The Init and Boot interfaces 25
3.8 Signatures of MainC and PowerupC 26
3.9 The Queue interface 27
3.10 Using a queue of 32-bit integers 27
3.11 Providing a 16-bit or a 32-bit queue 27
3.12 The Notify interface 28
3.13 UserButtonC 28
3.14 Simplified Timer interface showing three commands and one event 29
3.15 PowerupC module code 30
3.16 The module PowerupToggleC 30
3.17 The PowerupToggleAppC configuration 31
3.18 Example uses of the components keyword 31
3.19 The Get interface 32
3.20 A self-incrementing counter 32
3.21 Generic module SineSensorC and generic configuration TimerMilliC 33
3.22 Instantiating a generic component 34
3.23 Signature of BitVectorC 34
3.24 QueueC signature 34
3.25 The Read interface 36
3.26 The split-phase Send interface 36
3.27 The Send interface 38
xii List of code examples
3.28 The Receive interface 39
3.29 The signature of PoolC 41
3.30 CC2420 packet header 42
3.31 The dreaded “packed” attribute in the 1.x MintRoute library 43
3.32 The CC2420 header 44
3.33 TinyError.h, a typical nesC header file 45
3.34 Including a header file in a component 45
3.35 Indirectly including a header file 46
3.36 Fancy.nc: C preprocessor example 46
3.37 FancyModule.nc: C preprocessor pitfalls 47
3.38 Fancy.h: the reliable way to use C preprocessor symbols 47
3.39 Using a C library function 47
4.1 Signature of part of the CC1000 radio stack 49
4.2 The PowerupToggleAppC configuration revisited 51
4.3 C code generated from the PowerupToggleAppC configuration 51
4.4 The LedsC configuration 52
4.5 CC2420ReceiveC’s use of the as keyword 53
4.6 Naming generic component instances 54
4.7 MainC and LedsP 55
4.8 Valid alternate of PowerupToggleAppC 55
4.9 Invalid alternate of PowerupToggleAppC 55
4.10 LedsC revisited 56
4.11 BlinkC signature 56
4.12 The RandomC configuration 57
4.13 The RandomMlcgC signature 58
4.14 Seed initialization in RandomMlcgP 59
4.15 ActiveMessageC for the CC2420 61
4.16 The signature of CC2420ActiveMessageC 62
4.17 Fan-out on CC2420TransmitC’s Init 63
4.18 StdControl and SplitControl initialization interfaces 64
4.19 Why the metaphor of “wires” is only a metaphor 65
4.20 The combine function for error_t 66
4.21 Fan-out on SoftwareInit 67
4.22 Resulting code from fan-out on SoftwareInit 67
4.23 AMSenderC signature 68
4.24 RadioCountToLedsAppC 68
4.25 PoolC 69
4.26 Exposing a generic component instance as a singleton 70
5.1 The main TinyOS scheduling loop from SchedulerBasicP.nc 72
5.2 A troublesome implementation of a magnetometer sensor 76
5.3 Signal handler that can lead to an infinite loop 77
5.4 An improved implementation of FilterMagC 77
6.1 Anti-theft: simple flashing LED 80
6.2 The Leds interface 80
List of code examples xiii
6.3 The Boot interface 81
6.4 The full Timer interface 81
6.5 WarningTimer.fired with drift problem fixed 82
6.6 Anti-Theft: application-level configuration 83
6.7 The Read interface 84
6.8 Anti-theft: detecting dark conditions 84
6.9 Anti-Theft: wiring to light sensor 86
6.10 ReadStream Interface 87
6.11 Anti-theft: detecting movement 88
6.12 The AMSend interface 90
6.13 Anti-Theft: reporting theft over the radio 91
6.14 The SplitControl interface 92
6.15 The Receive interface 93
6.16 Anti-Theft: changing settings 93
6.17 Serial vs Radio-based AM components 94
6.18 The Send interface 96
6.19 Anti-Theft: reporting theft over a collection tree 96
6.20 DisseminationValue interface 97
6.21 Anti-Theft: settings via a dissemination tree 97
6.22 The StdControl interface 97
6.23 The DisseminationUpdate interface 99
6.24 AntiTheft base station code: disseminating settings 99
6.25 The RootControl interface 100
6.26 AntiTheft base station code: reporting thefts 101
6.27 AntiTheft base station wiring 101
6.28 ConfigStorageC signature 102
6.29 Mount interface for storage volumes 103
6.30 ConfigStorage interface 103
6.31 Anti-Theft: reading settings at boot time 104
6.32 Anti-Theft: saving configuration data 105
6.33 BlockStorageC signature 106
6.34 The BlockWrite interface 106
6.35 Simultaneously sampling and storing to flash
(most error checking omitted) 108
6.36 The BlockRead interface 108
6.37 LogStorageC signature 108
6.38 The LogWrite interface 109
6.39 The LogWrite interface 110
6.40 The LogRead interface 111
7.1 Serial AM Packet layout 113
7.2 TestSerial packet layout 114
7.3 Backing array methods 115
7.4 Sending packets with mig and MoteIF 117
7.5 Interface for handling received packets 117
xiv List of code examples
7.6 Receiving packets with mig and MoteIF 117
7.7 Constants and packet layout for Oscillscope application 118
7.8 Class generated by ncg 119
7.9 Simplified code to save received samples 119
7.10 Reliable transmission protocol in Java – transmission 121
7.11 Reliable transmission protocol in Java – transmission 123
7.12 A reliable TestSerial.java 125
8.1 Instantiation within a generic configuration 130
8.2 The fictional component SystemServiceVectorC 131
8.3 QueueC excerpt 131
8.4 A generic constant sensor 132
8.5 Queue interface (repeated) 133
8.6 QueueC implementation 133
8.7 Representing an ADT through an interface in TinyOS 1.x 135
8.8 Timers without parameterized interfaces 135
8.9 Timers with a single interface 136
8.10 HilTimerMilliC signature 137
8.11 ActiveMessageC signature 138
8.12 Signature of TestAMC 138
8.13 Wiring TestAMC to ActiveMessageC 138
8.14 A possible module underneath ActiveMessageC 139
8.15 Parameterized interface syntax 140
8.16 Dispatching on a parameterized interface 140
8.17 How active message implementations decide on whether
to signal to Receive or Snoop 140
8.18 Defining a parameter 141
8.19 Wiring full parameterized interface sets 141
8.20 Default events in an active message implementation 142
8.21 nesC attributes 143
9.1 Partial HilTimerMilliC signature 146
9.2 VirtualizeTimerC 148
9.3 Instantiating VirtualizeTimerC 148
9.4 VirtualizeTimerC state allocation 149
9.5 The TimerMilliC generic configuration 151
9.6 TimerMilliP auto-wires HilTimerMilliC to Main.SoftwareInit 151
9.7 The Blink application 151
9.8 The full module-to-module wiring chain in Blink (BlinkC to
VirtualizeTimerC) 152
9.9 CC2420SpiC 153
9.10 CC2420SpiP 154
9.11 CC2420SpiC mappings to CC2420SpiP 154
9.12 The strobe implementation 155
9.13 The AMSenderC generic configuration 158
9.14 AMSendQueueEntryP 159
List of code examples xv
9.15 AMQueueP 159
9.16 AMSendQueueImplP pseudocode 160
9.17 BlockStorageC 161
9.18 The full code of HilTimerMilliC 163
9.19 VirtualizeTimerC virtualizes a single timer 164
10.1 AMReceiverC 169
10.2 VirtualizeTimerC 172
10.3 Telos ActiveMessageC 181
10.4 The Matchbox facade 184
10.5 The CC2420CsmaC uses a Facade 185
10.6 AlarmToTimerC implementation 190
11.1 The Send interface 192
11.2 The Leds interface 193
11.3 Toggling a state variable 193
11.4 A call sequence that could corrupt a variable 194
11.5 State transition that is not async-safe 194
11.6 Incrementing with an atomic statement 195
11.7 Incrementing with two independent atomic statements 195
11.8 The first step of starting the CC2420 radio 198
11.9 The handler that the first step of starting the CC2420 is complete 198
11.10 The handler that the second step of starting the CC2420 is complete 198
11.11 The handler that the third step of starting the CC2420 radio is complete 199
11.12 State transition so components can send and receive packets 199
11.13 The Resource interface 201
11.14 Msp430Spi0C signature 202
11.15 Msp320Adc12ClientC signature 202
11.16 The ResourceDefaultOwner interface 203
11.17 The ResourceConfigure interface 204
12.1 ActiveMessageC signature 212
12.2 Arbitration in Stm25pSectorC 215
12.3 McuSleepC: platform-specific sleep code 218
13.1 SynchronizerC: time synchronization for SoundLocalizer 225
13.2 The Counter interface 226
13.3 DetectorC: loud sound detection for SoundLocalizer 231
13.4 The Alarm interface 231
13.5 Atm128AdcSingle: low-level single-sample ATmega128 A/D
converter interface 232
13.6 The GeneralIO digital I/O pin interface 235
13.7 The I2CPacket interface for bus masters 236
TinyOS programming 1st Edition Philip Levis
Preface
This book provides an in-depth introduction to writing nesC code for the TinyOS
2.0 operating system. While it goes into greater depth than the TinyOS tutorials on
this subject, there are several topics that are outside its scope, such as the structure
and implementation of radio stacks or existing TinyOS libraries. It focuses on how
to write nesC code, and explains the concepts and reasons behind many of the
nesC and TinyOS design decisions. If you are interested in a brief introduction to
TinyOS programming, then you should probably start with the tutorials. If you’re
interested in details on particular TinyOS subsystems you should probably consult TEPs
(TinyOSEnhancementProposals),whichdetailthecorrespondingdesignconsiderations,
interfaces, and components. Both of these can be found in the doc/html directory of
a TinyOS distribution.
While some of the contents of this book are useful for 1.x versions of TinyOS , they
do have several differences from TinyOS 2.0 which can lead to different programming
practices. If in doubt, referring to the TEP on the subject is probably the best bet, as TEPs
often discuss in detail the differences between 1.x and 2.0.
For someone who has experience with C or C++, writing simple nesC programs is
fairly straightforward: all you need to do is implement one or two modules and wire
them together. The difficulty (and intellectual challenge) comes when building larger
applications. The code inside TinyOS modules is fairly analogous to C coding, but
configurations – which stitch together components – are not.
This book is a first attempt to explain how nesC relates to and differs from other C
dialects, stepping through how the differences lead to very different coding styles and
approaches. As a starting point, this book assumes that
1. you know C, C++, or Java reasonably well, understand pointers and that
2. you have taken an undergraduate level operating systems class (or equivalent) and
know about concurrency, interrupts, and preemption.
Of course, this book is as much a description of nesC as it is an argument for a particular
way of using the language to achieve software engineering goals. In this respect, it is the
product of thousands of hours of work by many people, as they learned and explored the
use of the language. In particular, Cory Sharp, Kevin Klues, and Vlado Handziski have
always pushed the boundaries of nesC programming in order to better understand which
practices lead to the simplest, most efficient, and robust code. In particular, Chapter 10
xviii Preface
is an edited version of a paper we wrote together, while using structs as a compile-time
checking mechanism in interfaces (as Timer does) is an approach invented by Cory.
This book is divided into four parts. The first part, Chapters 1–2, gives a high-level
overviewofTinyOSandthenesClanguage.Thesecondpart,Chapters3–7goesintonesC
and TinyOS at a level sufficient for writing applications. The third part, Chapters 8–13
goes into more advanced TinyOS and nesC programming, as is sometimes needed when
writing new low-level systems or high performance applications. The book ends with
an appendix summarizing the basic application-level TinyOS APIs.
Acknowledgements
We’dliketothankseveralpeoplefortheircontributionstothisbook.FirstisMikeHorton,
of Crossbow, Inc., who first proposed writing it. Second is Pablo Guerrero, who gave
detailed comments and corrections. Third is Joe Polastre of Moteiv, who gave valuable
feedbackonhowtobetterintroducegenericcomponents.Fourth,we’dliketothankPhil’s
father, who although he doesn’t program, read the entire thing! Fifth, John Regehr, Ben
Greenstein and David Culler provided valuable feedback on this expanded edition. Last
but not least, we would like to thank the TinyOS community and its developers. Many
of the concepts in this book – power locks, tree routing, and interface type checking –
are the work and ideas of others, which we merely present.
Chapter 10 of this book is based on: Software design patterns for TinyOS, in ACM
Transactions on Embedded Computing Systems (TECS), Volume 6, Issue 4 (September
2007), ©ACM, 2007. http://doi.acm.org/10.1145/1274858.1274860
TinyOS programming 1st Edition Philip Levis
Programming hints, condensed
Programming Hint 1 Use the “as” keyword liberally. (page 24)
Programming Hint 2 Never write recursive functions within a module. In combination
with the TinyOS coding conventions, this guarantees that all programs have bounded
stack usage. (page 38)
Programming Hint 3 Never use malloc and free. Allocate all state in components. If
your application requirements necessitate a dynamic memory pool, encapsulate it in a
component and try to limit the set of users. (page 38)
Programming Hint 4 When possible, avoid passing pointers across interfaces; when
this cannot be avoided only one component should be able to modify a pointer’s data at
any time. (page 39)
Programming Hint 5 Conserve memory by using enums rather than const variables for
integer constants, and don’t declare variables with an enum type. (page 42)
Programming Hint 6 Never, ever use the “packed” attribute in portable code. (page 43)
Programming Hint 7 Use platform-independent types when defining message
structures. (page 44)
Programming Hint 8 If you have to perform significant computation on a
platform-independent type or access it many (hundreds or more) times, temporarily
copy it to a native type. (page 44)
Programming Hint 9 Interfaces should #include the header files for the types they use.
(page 46)
Programming Hint 10 Always #define a preprocessor symbol in a header file. Use
#include to load the header file in all components and interfaces that use the symbol.
(page 47)
Programming Hint 11 If a component is a usable abstraction by itself, its name should
end with C. If it is intended to be an internal and private part of a larger abstraction,
its name should end with P. Never wire to P components from outside your package
(directory). (page 58)
Programming Hint 12 Auto-wire Init to MainC in the top-level configuration of a
software abstraction. (page 60)
Programming Hint 13 When using layered abstractions, components should not wire
across multiple abstraction layers: they should wire to a single layer. (page 63)
Programming Hint 14 Never ignore combine warnings. (page 68)
xxii Programming hints, condensed
Programming Hint 15 Keep tasks short. (page 74)
Programming Hint 16 If an event handler needs to make possibly long-executing
command calls, post a task to make the calls. (page 75)
Programming Hint 17 Don’t signal events from commands – the command should post
a task that signals the event. (page 77)
Programming Hint 18 Use a parameterized interface when you need to distinguish
callers or when you have a compile-time constant parameter. (page 141)
Programming Hint 19 If a component depends on unique, then #define the string to
use in a header file, to prevent bugs due to string typos. (page 149)
Programming Hint 20 Whenever writing a module, consider making it more
general-purpose and generic. In most cases, modules must be wrapped by configurations
to be useful, so singleton modules have few advantages. (page 165)
Programming Hint 21 Keep code synchronous when you can. Code should be async
only if its timing is very important or if it might be used by something whose timing is
important. (page 195)
Programming Hint 22 Keep atomic statements short, and have as few of them as
possible. Be careful about calling out to other components from within an atomic
statement. (page 199)
Part I
TinyOS and nesC
TinyOS programming 1st Edition Philip Levis
1 Introduction
This book is about writing TinyOS systems and applications in the nesC language. This
chapter gives a brief overview ofTinyOS and its intended uses.TinyOS is an open-source
project which a large number of research universities and companies contribute to.
The main TinyOS website, www.tinyos.net, has instructions for downloading and
installing the TinyOS programming environment. The website has a great deal of useful
information which this book doesn’t cover, such as common hardware platforms and
how to install code on a node.
1.1 Networked, embedded sensors
TinyOS is designed to run on small, wireless sensors. Networks of these sensors have the
potential to revolutionize a wide range of disciplines, fields, and technologies. Recent
example uses of these devices include:
Golden Gate Bridge safety High-speed accelerometers collect synchonized data on
the movement of and oscillations within the structure of San Francisco’s Golden Gate
Bridge. This data allows the maintainers of the bridge to easily observe the structural
health of the bridge in response to events such as high winds or traffic, as well as quickly
assess possible damage after an earthquake [10]. Being wireless avoids the need for
installing and maintaining miles of wires.
Volcanic monitoringAccelerometers and microphones observe seismic events on the
Reventador and Tungurahua volcanoes in Ecuador. Nodes locally compare when they
observe events to determine their location, and report aggregate data to a camp several
kilometers away using a long-range wireless link. Small, wireless nodes allow geologists
and geophysicists to install dense, remote scientific instruments [30], obtaining data that
answers other questions about unapproachable environments.
Data center provisioning Data centers and enterprise computing systems require
huge amounts of energy, to the point at which they are placed in regions that have low
power costs. Approximately 50% of the energy in these systems goes into cooling, in
part due to highly conservative cooling systems. By installing wireless sensors across
machine racks, the data center can automatically sense what areas need cooling and
can adjust which computers do work and generate heat [19]. Dynamically adapting
4 Introduction
patch of sensors data sink gateway Internet
sensor code
(nesC/TinyOS)
base station code
(nesC/TinyOS)
gateway code
(Java, C, ...)
Figure 1.1 A typical sensor network architecture. Patches of ultra-low power sensors, running
nesC/TinyOS, communicate to gateway nodes through data sinks. These gateways
connect to the larger Internet.
these factors can greatly reduce power consumption, making the IT infrastructure more
efficient and reducing environmental impact.
While these three application domains are only a small slice of where networks
of sensors are used, they show the key differences between these networks and most
other computing systems. First, these “sensor networks” need to operate unattended for
long periods of time. Second, they gather data from and respond to an unpredictable
environment. Finally, for reasons of cost, deployment simplicity, and robustness,
they are wireless. Together, these three issues – longevity, embedment, and wireless
communication – cause sensor networks to use different approaches than traditional,
wired, and human-centric or machine-centric systems.
The sheer diversity of sensor network applications means that there are many network
architectures, but a dominant portion of deployments tend to follow a common one,
shown in Figure 1.1 [21, 26, 30] of ultra-low power sensors self-organized to form an
ad-hoc routing network to one or more data sink nodes. These sensor sinks are attached to
gateways, which are typically a few orders of magnitude more powerful than the sensors:
gateways run an embedded form of Linux, Windows, or other multitasking operating
system. Gateways have an Internet connection, either through a cell phone network,
long-distance wireless, or even just wired Ethernet.
Energy concerns dominate sensor hardware and software design. These nodes need to
be wireless, small, low-cost, and operate unattended for long periods. While it is often
possible to provide large power resources, such as large solar panels, periodic battery
replacement, or wall power, to small numbers of gateways, doing so to every one of
hundreds of sensors is infeasible.
1.1.1 Anatomy of a sensor node (mote)
Since energy consumption determines sensor node lifetime, sensor nodes, commonly
referred to as motes, tend to have very limited computational and communication
resources. Instead of a full-fledged 32-bit or 64-bit CPU with megabytes or gigabytes of
RAM, they have 8-bit or 16-bit microcontrollers with a few kilobytes of RAM. Rather
than gigahertz, these microcontrollers run at 1–10 megahertz. Their low-power radios
1.2 TinyOS 5
Antenna Radio Circuitry USB Serial
Expansion
Connector
Sensors
Figure 1.2 A Telos sensor produced by Moteiv. The top of the node has the radio, sensors, and circuitry for
the USB connector. The bottom, not shown, has the processor and flash storage chip. The
antenna is part of the printed circuit board (PCB).
can send tens to hundreds of kilobits per second (kbps), rather than 802.11’s tens of
megabits. As a result, software needs to be very efficient, both in terms of CPU cycles
and in terms of memory use.
Figure 1.2 shows a sample node platform, the Telos , which is designed for easy
experimentation and low-power operation. It has a TI MSP430 16-bit microcontroller
with 10 kB of RAM and 48 kB of flash program memory. Its radio, a TI CC2420 which
follows the IEEE 802.15.4 standard, can send up to 250 kbps. In terms of power, the
radio dominates the system: on a pair of AA batteries, a Telos can have the radio on for
about four days. Lasting longer than four days requires keeping the node in a deep sleep
state most of the time, waking only when necessary, and sleeping as soon as possible.
Theothermotediscussedinthisbook,themicazfromCrossbowTechnologyissimilar:
it has an Atmel ATmega128 8-bit microcontroller with 4 kB of RAM, 128 kB of flash
program memory, uses the same CC2420 radio chip, also runs off a pair of AA batteries
and has a similar power consumption profile.
Networks, once deployed, gather data uninterrupted for weeks, months, or years.
As the placement of sensors is very application-specific, it is rare for networks to
need to support multiple concurrent applications, or even require more than the
occasional reprogramming. Therefore, unlike general-purpose computing systems,
which emphasize run-time flexibility and composability, sensor network systems tend
to be highly optimized. Often, the sensor suite itself is selected for the specific
application:volcanicmonitoringusesaccelerometersandmicrophones,whiledatacenter
provisioning uses temperature sensors.
1.2 TinyOS
TinyOS is a lightweight operating system specifically designed for low-power wireless
sensors. TinyOS differs from most other operating systems in that its design focuses
on ultra low-power operation. Rather than a full-fledged processor, TinyOS is designed
6 Introduction
for the small, low-power microcontrollers motes have. Furthermore, TinyOS has very
aggressive systems and mechanisms for saving power.
TinyOS makes building sensor network applications easier. It provides a set of
importantservicesandabstractions,suchassensing,communication,storage,andtimers.
It defines a concurrent execution model, so developers can build applications out of
reusable services and components without having to worry about unforeseen interactions.
TinyOS runs on over a dozen generic platforms, most of which easily support adding
new sensors. Furthermore, TinyOS’s structure makes it reasonably easy to port to new
platforms.
TinyOS applications and systems, as well as the OS itself, are written in the nesC
language. nesC is a C dialect with features to reduce RAM and code size, enable
significant optimizations, and help prevent low-level bugs like race conditions. Chapter 2
goes into the details on how nesC differs significantly from other C-like languages, and
most of this book is about how to best use those features to write robust, efficient code.
1.2.1 What TinyOS provides
At a high level, TinyOS provides three things to make writing systems and applications
easier:
• a component model, which defines how you write small, reusable pieces of code and
compose them into larger abstractions;
• a concurrent execution model, which defines how components interleave their
computations as well as how interrupt and non-interrupt code interact;
• application programming interfaces (APIs), services, component libraries and an
overall component structure that simplify writing new applications and services.
The component model is grounded in nesC. It allows you to write pieces of reusable
code which explicitly declare their dependencies. For example, a generic user button
component that tells you when a button is pressed sits on top of an interrupt handler. The
component model allows the button implementation to be independent of which interrupt
that is – e.g. so it can be used on many different hardware platforms – without requiring
complex callbacks or magic function naming conventions. Chapter 2 and Chapter 3
describe the basic component model.
TheconcurrentexecutionmodelenablesTinyOStosupportmanycomponentsneeding
to act at the same time while requiring little RAM. First, every I/O call in TinyOS is
split-phase: rather than block until completion, a request returns immediately and the
caller gets a callback when the I/O completes. Since the stack isn’t tied up waiting
for I/O calls to complete, TinyOS only needs one stack, and doesn’t have threads.
Instead, Chapter 5 introduces tasks, which are lightweight deferred procedure calls. Any
component can post a task, whichTinyOS will run at some later time. Because low-power
devices must spend most of their time asleep, they have low CPU utilization and so in
practice tasks tend to run very soon after they are posted (within a few milliseconds).
Furthermore, because tasks can’t preempt each other, task code doesn’t need to worry
about data races. Low-level interrupt code (discussed in the advanced concurrency
1.3 Example application 7
chapter, Chapter 11) can have race conditions, of course: nesC detects possible data
races at compile-time and warns you.
Finally, TinyOS itself has a set of APIs for common functionality, such as sending
packets, reading sensors, and responding to events. Uses of these are sprinkled
throughpout the entire book, and presented in more detail in Chapter 6 and Appendix 1.
In addition to programming interfaces, TinyOS also provides a component structure and
component libraries. For example, Chapter 12 describes TinyOS’s HardwareAbstraction
Architecture (HAA), which defines how to build up from low-level hardware (e.g. a
radio chip) to a hardware-independent abstraction (e.g. sending packets). Part of this
component structure includes resource locks, covered in Chapter 11, which enable
automatic low-power operation, as well as the component libraries that simplify writing
such locks.
TinyOS itself is continually evolving. Within the TinyOS community, “Working
Groups” form to tackle engineering and design issues within the OS, improving existing
services and adding new ones. This book is therefore really a snapshot of the OS in
time. As Chapter 12 discusses and Appendix 1 presents, TinyOS has a set of standard,
stable APIs for core abstractions, but this set is always expanding as new hardware and
applications emerge. The best way to stay up to date with TinyOS is to check its web page
www.tinyos.net and participate in its mailing lists. The website also covers advanced
TinyOS and nesC features which are well beyond the scope of this book, including
binary components, over-the-air reprogramming services, debugging tools, and a nesC
reference manual.
1.3 Example application
To better understand the unique challenges faced by sensor networks, we walk through a
basic data-collection application. Nodes running this application periodically wake up,
sample some sensors, and send the data through an ad hoc collection tree to a data sink
(as in Figure 1.1). As the network must last for a year, nodes spend 99% of their time in
a deep sleep state.
In terms of energy, the radio is by far the most expensive part of the node. Lasting a year
requires telling the radio to be in a low power state. Low power radio implementation
techniques are beyond the scope of this book, but the practical upshot is that packet
transmissions have higher latency. [23]
Figure 1.3 shows the four TinyOS APIs the application uses: low power settings for
the radio, a timer, sensors, and a data collection routing layer. When TinyOS tells the
application that the node has booted, the application code configures the power settings
on the radio and starts a periodic timer. Every few minutes, this timer fires and the
application code samples its sensors. It puts these sensor values into a packet and calls
the routing layer to send the packet to a data sink. In practice, applications tend to be
more complex than this simple example. For example, they include additional services
such as a management layer which allows an administrator to reconfigure parameters
and inspect the state of the network, as well as over-the-air programming so the network
8 Introduction
Application
Timer Routing
Sensors Radio
Figure 1.3 Example application architecture. Application code uses a timer to act periodically, sensors to
collect data, and a routing layer to deliver data to a sink.
can be reprogrammed without needing to collect all of the nodes. However, these four
abstractions – power control, timers, sensors, and data collection – encompass the entire
datapath of the application.
1.4 Compiling and installing applications
You can download the latest TinyOS distribution, the nesC compiler, and other tools at
www.tinyos.net. Setting up your programming environment is outside the scope of
this book; the TinyOS website has step-by-step tutorials to get you started. One part of
TinyOS is an extensive build system for compiling applications. Generally, to compile a
program for a sensor platform, one types make <platform>, e.g. make telosb.
This compiles a binary. To install that binary on a node, you plug the node into your
PC using a USB or serial connection, and type make <platform> install. The
tutorials go into compilation and installation options in detail.
1.5 The rest of this book
The rest of this book goes into how to program in nesC and write TinyOS applications.
It is divided into three parts. The first is a short introduction to the major programming
concepts of nesC. The second part addresses basic application programming using
standardTinyOSAPIs.Thethirdpartdigsalittledeeper,andlooksintohowthoseTinyOS
APIs are implemented. For example, the third part describes how TinyOS abstracts
hardware, so you can write a driver for a new sensor.
Chapter by chapter, the book is structured as follows:
• Chapter 1 is this chapter.
• Chapter 2 describes the major way that nesC breaks from C and C-like languages:
how programs are built out of components, and how components and interfaces help
manage programs’ namespaces.
• Chapter 3 presents components and how they interact via interfaces.
• Chapter 4 goes into greater detail into configurations, components which connect
other components together.
• Chapter 5 covers the basic TinyOS execution model and gives guidance on how and
when to use tasks.
1.5 The rest of this book 9
• Chapter 6 takes the material from the prior three chapters and brings it together into
an example of writing a fully-fledged application that sends an alarm when a node
observes a change in its environment. In the process, it covers the major TinyOS APIs
(timing, sensing, communication, and storage).
• Chapter 7 details the PC-side tools for communicating with nodes connected over
the serial port, and covers the TinyOS serial stack and packet formats.
• Chapter 8 introduces more advanced component topics, such as parameterized
interfaces and attributes. While applications typically don’t use these mechanisms,
they are indispensable when writing reusable libraries and systems.
• Chapter 9 goes into wiring parameterized interfaces, which form the basis for most
reusable systems.After describing the basic mechanisms for managing interface keys,
it goes through four examples of increasing complexity.
• Chapter 10 presents eight common TinyOS design patterns: commonly useful and
powerful ways of organizing components.
• Chapter 11 concludes the advanced programming topics by covering concurrency. It
describes asynchronous code, the TinyOS task model, and power locks.
• Chapter 12 describes the Hardware Abstraction Architecture (HAA), the
three-level hierarchy TinyOS uses to raise low-level hardware abstractions to
hardware-independent, application-level services.
• Chapter 13 goes step-by-step through an advanced application that identifies the
location of an event based on when nodes sense it. It uses lower-layer interfaces to
implement time synchronization and high-frequency sampling.
• Appendix gives a concise overview of major TinyOS application interfaces.
Throughout the book, you will find programming hints: general best-use practices
that we’ve distilled from the many users of TinyOS and nesC. These are all listed on the
sheet at the front of the book.
Finally, the complete source code for example applications presented in this book (in
Chapters 6, 7 and 13) is available in TinyOS’s contributed code directory, under the name
“TinyOS Programming” – see www.tinyos.net for details.
2 Names and program structure
Program structure is the most essential and obvious difference between C and nesC.
C programs are composed of variables, types, and functions defined in files that are
compiled separately and then linked together. nesC programs are built out of components
that are connected (“wired”) by explicit program statements; the nesC compiler connects
and compiles these components as a single unit.To illustrate and explain these differences
in how programs are built, we compare and contrast C and nesC implementations of two
very simple “hello world”-like mote applications, Powerup (boot and turn on a LED)
and Blink (boot and repeatedly blink a LED).
2.1 Hello World!
The closest mote equivalent to the classic “Hello World!” program is the “Powerup”
application that simply turns on one of the motes LEDs at boot, then goes to sleep.
A C implementation of Powerup is fairly simple:
# include " mote .h"
int main ()
{
mote_init ();
led0_on ();
sleep ();
}
Listing 2.1 Powerup in C
The Powerup application is compiled and linked with a “mote” library which provides
functions to perform hardware initialization (mote_init), LED control (led0_on) and put
the mote in to a low-power sleep mode (sleep). The “mote.h” header file simply provides
declarations of these and other basic functions. The usual C main function is called
automatically when the mote boots.1
1 The C compiler, library, and linker typically arrange for this by setting the mote’s hardware reset vector to
point to a piece of assembly code that sets up a C environment, then calls main.
2.1 Hello World! 11
The nesC implementation of Powerup is split into two parts. The first, the PowerupC
module, contains the executable logic of Powerup (what there is of it …):
module PowerupC {
uses interface Boot ;
uses interface Leds ;
}
implementation {
event void Boot . booted () {
call Leds . led0On ();
}
}
Listing 2.2 PowerupC module in nesC
This code says that PowerupC interacts with the rest of the system via two interfaces,
Boot and Leds, and provides an implementation for the booted event of the Boot
interface that calls the led0On2 command of the Leds interface. Comparing with the
C code, we can see that the booted event implementation takes the place of the main
function, and the call to the led0On command the place of the call to the led0_on library
function.
This code shows two of the major differences between nesC and C: where C programs
are composed of functions, nesC programs are built out of components that implement a
particular service (in the case of PowerupC, turning a LED on at boot-time). Furthermore,
C functions typically interact by calling each other directly, while the interactions
between components are specified by interfaces: the interface’s user makes requests
(calls commands) on the interface’s provider, the provider makes callbacks (signals
events) to the interface’s user. Commands and events themselves are like regular
functions (they can contain arbitrary C code); calling a command or signaling an event
is just a function call. PowerupC is a user of both Boot and Leds; the booted event is
a callback signaled when the system boots, while the led0On is a command requesting
that LED 0 be turned on.
nesC interfaces are similar to Java interfaces, with the addition of a command or
event keyword to distinguish requests from callbacks:
interface Boot } {
event void } booted ();
}
interface Leds {
command void led0On ();
command void led0Off ();
2 LEDs are numbered in TinyOS, as different platforms have different color LEDs.
12 Names and program structure
command void led0Toggle ();
...
}
Listing 2.3 Simple nesC interfaces
The second part of Powerup, the PowerupAppC configuration, specifies how
PowerupC is connected to TinyOS’s services:
configuration PowerupAppC { }
implementation {
components MainC , LedsC , PowerupC ;
MainC . Boot -> PowerupC . Boot ;
PowerupC . Leds -> LedsC . Leds ;
}
Listing 2.4 PowerupAppC configuration in nesC
This says that the PowerupAppC application is built out of three components
(modules or configurations), MainC (system boot), LedsC (LED control), and PowerupC
(our powerup module). PowerupAppC explicitly specifies the connections (or wiring)
betweentheinterfacesprovidedandusedbythesecomponents.WhenMainChasfinished
booting the system it signals the booted event of its Boot interface, which is connected
by the wiring in PowerupAppC to the booted event in PowerupC. This event then
calls the led0On command of its Leds interface, which is again connected (wired) by
PowerupAppC to the Leds interface provided by LedsC. Thus the call turns on LED 0.
The resulting component diagram is shown in Figure 2.1 – this diagram was generated
automatically from PowerupAppC by nesdoc, nesC’s documentation generation tool.
PowerupAppCillustratesthethirdmajordifferencebetweenCandnesC:wiringmakes
the connections expressed by linking the C version of Powerup with its “mote” library
explicit. In the C version, Powerup calls a global function named led0_on which is
connected to whatever library provides a function with the same name; if two libraries
PowerupC
MainC LedsC
Boot Leds
Figure 2.1 Wiring Diagram for Powerup application
2.2 Essential differences: components, interfaces, and wiring 13
.nc
.nc
.nc app.c binary
nesC
compiler
Native C
compiler
Figure 2.2 The nesC compilation model. The nesC compiler loads and reads in nesC components, which it
compiles to a C file. This C file is passed to a native C compiler, which generates a mote binary.
provide such a function then (typically) the first one named on the linker command line
“wins.” Using a nesC configuration, the programmer instead explicitly selects which
component’s implementation of the function to use.
The nesC compiler can take advantage of this explicit wiring to build highly optimized
binaries. Current implementations of the nesC compiler (nesc1) take nesC files
describing components as input and output a C file. The C file is passed to a native C
compiler that can compile to the desired microcontroller or processor. Figure 2.2 shows
this process. The nesC compiler carefully constructs the generated C file to maximize the
optimization abilities of the C compiler. For example, since it is given a single file, the
C compiler can freely optimize across call boundaries, inlining code whenever needed.
The nesC compiler also prunes dead code which is never called and variables which are
never accessed: since there is no dynamic linking in nesC, it has a complete picture of
the application call graph. This speeds the C compilation and reduces program size in
terms of both RAM and code.
2.2 Essential differences: components, interfaces, and wiring
The three essential differences between C and nesC – components, interfaces, and
wiring – all relate to naming and organizing a program’s elements (variables, functions,
types, etc). In C, programs are broken into separate files which are connected via a global
namespace: a symbol X declared in one file is connected by the linker to a symbol X
defined in another file. For instance, if file1.c contains:
extern void g( void ); /* declaration of g */
int main () /* definition of main */
{
g(); g ();
}
and file2.c contains:
void g( void )
{
printf (" hello world !");
}
14 Names and program structure
then compiling and linking file1.c and file2.c connects the calls to g() in main
to the definition of g in file2.c. The resulting program prints “hello world!” twice.
Organizing symbols in a global namespace can be tricky. C programmers use a number
oftechniquestosimplifythistask,includingheaderfilesandnamingconventions.Header
files group declarations so they can be used in a number of files without having to retype
them, e.g. a header file file1.h for file1.c would normally contain:
# ifndef FILE1_H
# define FILE1_H
extern void g( void ); /* declaration of g */
# endif
Naming conventions are designed to avoid having two different symbols with the
same name. For instance, types are often suffixed with _t guaranteeing that a type and
function won’t have the same name. Some libraries use a common prefix for all their
symbols, e.g. Gtk and gtk_ for the GTK+ graphical toolkit. Such prefixes remind users
that functions are related and avoid accidental name collisions with other libraries, but
make programs more verbose.
nesC’s components provide a more systematic approach for organizing a program’s
elements. A component (module or configuration) groups related functionality (a timer,
a sensor, system boot) into a single unit, in a way that is very similar to a class in an
object-oriented language. For instance, TinyOS represents its system services as separate
components such as LedsC (LED control, seen above), ActiveMessageC (sending and
receivingradiomessages),etc.Onlytheservice(component)nameisglobal,theservice’s
operations are named in a per-component scope:ActiveMessageC.SplitControl starts and
stops the radio, ActiveMessageC.AMSend sends a radio message, etc.
Interfaces bring further structure to components: components are normally specified
in terms of the set of interfaces (Leds, Boot, SplitControl,AMSend) that they provide and
use, rather than directly in terms of the actual operations. Interfaces simplify and clarify
code because, in practice, interactions between components follow standard patterns:
many components want to control LEDs or send radio messages, many services need
to be started or stopped, etc. Encouraging programmers to express their components in
terms of common interfaces also promotes code reuse: expressing your new network
protocol in terms of the AMSend message transmission interface means it can be used
with existing applications, using AMSend in your application means that it can be used
with any existing or future network protocol.
Rather than connect declarations to definitions with the same name, nesC programs
use wiring to specify how components interact: PowerupAppC wired PowerupC’s Leds
interface to that provided by the LedsC component, but a two-line change could switch
that wiring to the NoLedsC component (which just does nothing):
components PowerupC , NoLedsC ;
PowerupC . LedsC -> NoLedsC . Leds ;
without affecting any other parts of the program that wish to use LedsC. In C, one could
replace the “mote” library used by Powerup by a version where the LED functions did
nothing, but that change would affect all LED users, not just Powerup.
2.3 Wiring and callbacks 15
2.3 Wiring and callbacks
Leaving the component connection decisions to the programmer does more than just
simplify switching between multiple service implementations. It also provides an
efficient mechanism for supporting callbacks, as we show through the example of timers.
TinyOS provides a variable number of periodic or deadline timers; associated with each
timer is a callback to a function that is executed each time the timer fires. We first look
at how such timers would be expressed in C, by modifying Powerup to blink LED 0 at
2 Hz rather than turn it on once and for all:
# include " mote .h"
timer_t mytimer ;
void blink_timer_fired ( void )
{
leds0_toggle ();
}
int main ()
{
mote_init ();
timer_start_periodic (& mytimer , 250 , blink_timer_fired );
sleep ();
}
Listing 2.5 Powerup with blinking LED in C
In this example, the Blink application declares a global mytimer variable to hold
timer state, and calls timer_start_periodic to set up a periodic 250 ms timer. Every time
the timer fires, the timer implementation performs a callback to the blink_timer_fired
function specified when the timer was set up. This function simply calls a library function
that toggles LED 0 on or off.
The nesC version of Blink is similar to the C version, but uses interfaces and wiring
to specify the connection between the timer and the application:
module BlinkC {
uses interface Boot ;
uses interface Timer ;
uses interface Leds ;
}
implementation {
event void Boot . booted () {
call Timer . startPeriodic (250);
}
event void Timer . fired () {
16 Names and program structure
call Leds . led0Toggle ();
}
}
Listing 2.6 Powerup with blinking LED in nesC (slightly simplified)
The BlinkC module starts the periodic 250 ms timer when it boots. The connection
between the startPeriodic command that starts the timer and the fired event which blinks
the LED is implicitly specified by having the command and event in the same interface:
interface Timer {
command void startPeriodic ( uint32_t interval );
event void fired ();
...
}
Finally, this Timer must be connected to a component that provides an actual timer.
BlinkAppC wires BlinkC.Timer to a newly allocated timer MyTimer:
configuration BlinkAppC { }
implementation {
components MainC , LedsC , new TimerC () as MyTimer , BlinkC ;
BlinkC . Boot -> MainC . Boot ;
BlinkC . Leds -> LedsC . Leds ;
BlinkC . Timer -> MyTimer . Timer ;
}
Listing 2.7 Powerup with blinking LED configuration (slightly simplified)
In the C version the callback from the timer to the application is a run-time argument to
the timer_start_periodic function. The timer implementation stores this function pointer
in the mytimer variable that holds the timer’s state, and performs an indirect function
call each time the timer fires. Conversely, in the nesC version, the connection between
the timer and the Blink application is specified at compile-time in BlinkAppC. This
avoids the need to store a function pointer (saving precious RAM), and allows the nesC
compiler to perform optimizations (in particular, inlining) across callbacks.
2.4 Summary
Table 2.1 summarizes the difference in how programs are structured in C, C++ and nesC.
In C, the typical high-level programming unit is the file, with an associated header file
that specified and documents the file’s behavior. The linker builds applications out of
files by matching global names; where this is not sufficient to express program structure
(e.g. for callbacks), the programmer can use function pointers to delay the decision of
which function is called at what point.
Another Random Document on
Scribd Without Any Related Topics
by the mate, who prevented the explosion that was about to take
place by informing him that the men had refused duty.
"Refused duty!" said the captain; "what can that mean?"
"Why, sir, they say they won't go to sea unless you ship a man in the
place of the one that died."
"But I can't now," said he; "the ship must go right to sea, and no
one would go on such a short notice."
"I've told them that, sir, but that villain, Brock, has made the rest
ugly."
Capt. Nelson returned on shore and spent half an hour in a vain
attempt to find a sailor who would go immediately to sea. Returning
on board he asked me to go into the forecastle and try to persuade
the men to turn to. I did what I could, but of course a boy's talk was
not much heeded, and I got rather scared myself by their curses and
threats. Then the mate came to the door and asked in a shaky voice,
"Are you going to turn to?"
"When that man comes aboard," was Brock's defiant answer.
Mr. Smith hastened back to report that they still refused duty, and
the captain hailed a passing boat and procured some Russians from
the "Captain of the 'Branvault,'" as the harbor-master is called. With
their assistance the ship was hauled to the Mole-head, and gave her
hawser to the towboat that was waiting outside. Then the Russians
stepped ashore, I took the wheel, the mates cast off the lines, and
we proceeded in tow of the steamer.
When fairly off, the captain told the mate to call all hands aft.
Standing by the cabin door he made an address to them, offering to
divide among them the wages that would have come to the dead
sailor, had he lived to complete the voyage.
Some of the men were inclined to give in, but Brock muttered, "We
don't want a dead man's wages."
"Well," said the captain, "I'll give you what I should have paid
another man if I had shipped one."
"Oh, we've been humbugged that way before, Cap'n," said Brock,
who turned and went forward, followed by the rest of the crew,
leaving the captain in the midst of another conciliatory harangue.
The ship was soon abreast of Tollbaken, ten miles from Cronstadt.
The wind was dead ahead; and having nominally sailed, the captain
decided to come to anchor and wait for the wind and crew to favor
him.
The mate asked the men if they would turn to and let go the anchor;
and thinking they would thus gain their point, and also their dinner,
they consented. The steamer was cast off and the ship brought to
anchor.
The crew were then allowed to get their dinner, but when called on
to work, they again refused. The captain was greatly troubled, and
so much at a loss what to do, that he appealed to me for advice. I
felt rather flattered by his consideration, and suggested that he
should put the men in irons. He was afraid to try that, so I proposed
that he should give them nothing to eat till they resumed duty.
When supper-time came they went to the galley, and being refused,
Brock marched aft with his tin pot in hand, and with the coolest
impudence, asked the captain if they were not to be allowed any
supper.
"Not till you turn to," was the reply.
The man then put on an air of injured innocence and declared it was
a shame to try to starve men to death. But he sauntered forward,
and the men turned in, laughing at the way they had "waxed the old
man," but feeling a little concerned on the score of eating.
At nine o'clock in the evening, the wind hauled fair. The captain went
to the forecastle, and after fifteen minutes spent in argument upon
the propriety of their going to work, the promise of some tea, and
other fair words, prevailed upon the men to get the ship under way,
and the passage was fairly begun.
We passed through the Baltic and by Elsinore without any
remarkable occurrence, except the increased independence and
insolence of the crew. They felt that the Cronstadt disturbance had
proved there was no fight in the officers, and some of the crew
showed more zeal in taking their comfort than in obeying orders.
Brock particularly distinguished himself. He boasted in the forecastle
that he was going to try to induce an officer to strike him, in order
that he might raise some money by a lawsuit on arriving in New
York. One day the ship was running before a strong breeze, under
the main-top-gallant-sail. Brock was at the wheel, and, being a
miserable helmsman, was letting the ship yaw about two points each
side of her course.
"Keep her straight," said the captain.
"I should like to see any one keep her any straighter," was Brock's
answer; and upon this the captain took hold of the wheel to prove
that it could be done. Instead of stopping to witness the proof, Brock
started forward.
"Come back here!" shouted the captain.
"One's enough to steer the ship," was the polite answer, and the
fellow made for the forecastle, leaving the captain working the
wheel, unable to leave it until relieved. The mate, finding out the
trouble, went to the forecastle and saw Brock leisurely lighting his
pipe.
"Go aft and take the wheel again! What business have you got
here?"
"Don't you fret; I'll come out when I get ready," said Brock. The
mate turned away and sent another sailor to relieve the captain.
After Brock had finished his smoke, he appeared again on deck, and
politely asked Mr. Smith if he had a job for him. The mate gave him
a few of his opinions about his behavior, and set him at work aloft.
That night, in the first watch, I was keeping the mate company on
deck, and hearing Mr. Smith's complaints about Brock. "Why don't
you knock him down?" said I. "That's the only kind of treatment
such a man can understand."
"I'll tell you why I don't," said the mate. "About five years ago I was
mate of the ship "Neptune" in the Liverpool trade. We hove up our
anchor in the River Mersey and were being towed out to sea. I was
anxious to get the anchor catted as soon as possible, as the pilot
wanted sail made on the ship, and I had all the crew on the
forecastle, heaving on the capstan. An ugly-looking Liverpool
Irishman, called Jim Kelley, was holding the turn, and just as the
anchor was about up to the cat-head he let go the rope; it flew
around the capstan at a lively rate, and the anchor went down.
"I growled at him for it, and he said it slipped away from him. We
went at it again, and had the anchor half-way up, when Kelley
surged the fall and let it go again. It was raining at the time, and
things were very slippery, and he pleaded that as his excuse; but I
thought I saw mischief in his eye. The end of the fall had hit two of
the men pretty severe blows, as it flew around the capstan. I was
pretty mad by this time, and told him if he did that again I'd knock
his head off. I thought he'd hold on the next time, but just as I was
going to say, "Heave a pawl!" down went the anchor for the third
time. I heard the pilot rattling off a string of oaths as long as the
maintop-bow-line, and I stepped up to Kelley and gave him a touch
of my fist that sent him head first off the top-gallant forecastle on to
a pile of chain cable. He didn't feel like holding any more turns for a
day or two, you may bet, and the rest of the crew said it served him
right. But when we got into New York I was hauled up in court for it,
and had to pay fifty dollars fine. Now I've got a wife and five
children, and as good-looking ones as you'd wish to see they are,
too, though I say it, and my wages are all they have to support
them. That villain Brock, is a good deal of a sea-lawyer, and if I lay
my hand on him, it's only taking the bread out of my little ones'
mouths and giving him rum money. I made a vow after that time
that I'd never strike a man again."
"But what can you do," said I; "you ought to keep good discipline.
Hasn't the captain got any legal power to punish ugly sailors?"
"Yes," said Mr. Smith, "the captain has power, but he doesn't want to
be troubled, and it's considered the mate's place to keep the men
straight. Once I went to a captain and reported an impudent sailor,
and the only satisfaction I got was, "What did you come here for if
you can't take care of the crew," and I got turned out of the ship at
the end of the voyage. I made a vow then that I'd never complain to
the old man again; so between my two vows I don't see that I've
got much chance with a sailor that's bent on making a row. If this
ai'n't a dog's life, I'd like to know what it is."
All the way across the Atlantic the sailors may be said to have had
charge of the ship, and did about as they pleased. Brock's insolence
was beyond all bounds, and it seemed incredible that it should be
submitted to by the captain and officers. He was evidently in a
desperate mood to get struck, and one evening at eight o clock,
when the captain kept his watch up a few minutes to take in the
top-gallantsails, as a stormy night was coming on, Brock stepped up
to him and said, "Cap'n, it's too late for you to try and humbug us
now. It's our watch below." The captain sputtered some bad words
at him, and told him he was no sailor: but the hoped-for blow was
not given.
The passage ended at last, and New York was reached, none too
soon for all on board. The day after arrival, the crew came to the
ship to be paid off, and Brock called the mate aside and made this
startling speech: "Mr. Smith, I want to beg your pardon for the way I
behaved on this voyage. You're the kindest man ever I sailed with,
and I know I ought to be ashamed of myself. I can show you the
marks on my head where the last mate I was with split it open with
a belaying pin, and I deserved it too. You'd have done right if you
had served me the same way. What would my good old mother have
said if she had known what a wretch I have been! She used to pray
with me, and beg me to be a good man. Now that she's dead, her
words sometimes haunt me, and I have made up my mind that I'll
be a different man for the rest of my life." A tear stood in his eye,
and good Mr. Smith took his hand and said, "I don't bear you no ill-
will, Brock. I don't harbor malice towards nobody living. If a man
should cut my throat, I believe I'd forgive him the next minute." As
he turned away, he caught a whiff of Brock's breath, and the
suspicion came sadly to his mind that this repentance was not so
much the result of piety as of whiskey.
This story reminds me of a little incident that occurred in Bombay
when I was mate of the "Lizzie Oakford." There were two English
ships anchored, one on each side of us. It was a calm morning, and
we could hear some of the words spoken on board these vessels. A
little after breakfast our attention was attracted to the ship on the
port side, by the sound of angry voices. The captain was having an
altercation with some of his crew, and very soon passed from words
to blows. He "ended" four or five of them over, and with every stroke
of his fist we could hear him swear about the Act of Parliament. In
the course of half an hour we heard a row on board the ship on the
starboard side, and looking towards her we saw a number of her
crew on the poop-deck. One of the sailors had seized hold of the
mate's coat-tail, and was whirling him around in a circle, while
another, with a folded strip of canvas, belabored his back every time
he flew past. Our second mate was so indignant at this insult to his
cloth that he wanted to board the vessel and fight the sailors on his
own account, but he said he should want to "lick the mate too."
"There," said he, "are the two extremes, and we are the middle. In
one ship the officers abuse the sailors, and in the other the sailors
abuse the officers. Here there hasn't been much of either yet awhile,
though I think the old shell-backs have got a little the best of it."
We ran down the trades, and keeping well to the southward in order
to catch the "brave westerlies" as soon as possible, we came in sight
of Tristan d'Acunha, a noble, symmetrical mountain island, 8,326
feet high, its top covered with snow. We were becalmed in sight of it
for several hours, and enjoyed resting our eyes, wearied with gazing
for weeks upon the dancing water, by fixing them on this grand,
immovable mass. Books gave an interesting account of a colony
formed here; but we were not near enough to perceive any signs of
human life. The lazy rolling of the bark in the swell, made even the
idea of a residence on the snowy peak seem attractive, and there
was comfort in thinking of a future world which is to be all land.
A breeze, springing up from the north-east, gradually freshened. The
sea being quite smoothed down by the calm, we were able to carry
a press of canvas; and with all sail set and the yards braced up, the
bark lay down on her side, and made a run of 261 miles in 24 hours,
and the day after, she made 252 miles. The fore topgallantmast was
then found to be sprung, and a new one had to be put in its place.
While sending it up, we overtook and passed a brig, loafing along
under reefed topsails, evidently seeming to think it was blowing a
gale of wind, whereas we had our main-royal set. This showed why
some vessels make long passages.
We sped along swiftly, passing the Cape of Good Hope when 61 days
out, and running along the parallel of 40° S., a succession of gales
helped us onward. The weather was chilly, often wet and
disagreeable, but our good progress kept us cheerful. One night was
especially exhilarating, when running in a north-west gale, with the
wind quartering, under reefed canvas, the bark flying away, at the
rate of 14 knots, from wind, rain, thunder, lightning and towering
waves. There is some sublimity in a sailor's life, and this wild scene
was a good specimen of it. I enjoyed standing by the bitts and
singing at the top of my voice some hymns expressing trust in the
Creator, knowing that the noise of the elements made the sound
inaudible to the crew. As we neared Amsterdam Island, the weather
continued rainy, and there was no chance for observations by which
to verify our position. On the day I expected to pass it, the sun
appeared, most providentially, just at noon for a moment. I caught
the altitude with my sextant and found the latitude. But I had no
means of determining the longitude. We were a few miles south of
the latitude of the island, so I steered due east, keeping a hand on
the lookout to watch for the land, as I desired to sight it to verify the
reckoning and the chronometers. No land appeared; a dark night
was coming on, and I felt anxious at running down so nearly in the
latitude of the island; but at evening-time it was light, and at 6, p.m.,
we saw the noble mass of land, nearly three thousand feet high,
bearing off the weather-quarter. We had already sailed by it, within
five miles distance.
One feature of great interest in these latitudes is the presence of
sea-birds. The noble Albatross, the king of sea-birds, is almost
always in sight, floating in the air about the vessel, no matter how
fast she goes. Its wings seldom move, and what its propelling power
is, no one can tell. It seems to depend only on its volition. The
Stormy Petrel or "Mother Carey's Chicken," is here and everywhere
else on the ocean. The pretty white and black Cape Pigeons flock in
the wake. We caught several of these with small fish-hooks, and
tried their value as component parts of a pigeon-pie, but the flavor
was rather strong and oily. The homely, black Cape Hens are
numerous also. They always bring to my mind a scene witnessed on
a former voyage. Coming on deck one Sunday, I found the mate and
passengers engaged in tying pieces of pork and bits of red flannel at
each end of a string and throwing them overboard. The Cape Hens
greedily swallowed the pork, and several of them were flying about
with streamers hanging from their mouths; another trick was to tie
several pieces of pork to the same string. Two or three birds darting
at these, and each swallowing a piece, they would rise in the air tied
together. I took the part of the hens on this occasion, and let the
mate brace the yards for a while.
The weather was cool in these latitudes, and it was no longer
agreeable to sit on deck. Our evenings were usually passed in the
cabin, and I employed some of the hours in reading to the
passenger an account of my experiences in the ship Dublin. I
explained to him that it was written while I was officer of a ship, and
had no leisure to attempt literary embellishment. Its sole object was
to record the events relating to the management of the crew, and I
requested him to forbear criticism of its style.
CHAPTER III.
THE VOYAGE OF THE "DUBLIN."
MY first voyage, as officer, was made in the good ship "Dublin."
She was six hundred tons register, and of the style said to be built,
Down East, by the mile and sawed off. Her bow and stern were so
square, they gave an impression of truth to this statement, but for
all that she was a staunch, well built vessel, and though twenty-one
years old was still an able and trustworthy ship. Her worthy owner,
one of the merchant princes of Boston, used to go down on the
wharf and rub his hands with delight when the old "Dublin" came
into port. She was his favorite ship, and her blunt bow was more
attractive to him than the rakish model of the modern clippers. He
would tell how the copper bolts were driven into her, only one inch a
day, to make them "fit solid;" how the timbers were "scarfed" and
"dowelled," and many other things that it would need a ship
builder's manual to interpret. He considered a great honor had been
done me, by the permission to go to sea as third mate of her, and
shook his head with misgivings when he heard that the captain had
engaged so young and inexperienced an officer. I had been to sea
four voyages, one of them over fourteen months around the world,
before the mast. I could hand, reef and steer, and do the ordinary
work on the rigging, as well as most sailors, so I did not consider my
presumption very great.
Captain Streeter, her commander, was a fine-looking man of about
forty years. He was tall and well formed, with dark complexion, black
hair, beard and moustache, and a coal-black, flashing eye that
bespoke a strong will and a passionate nature. He was very fluent in
speech, and gave the impression on a first hearing that he was what
sailors call "a blower."
When he engaged me, he gave a long and impressive harangue. He
didn't want an officer that was afraid of sailors, but at the same time
he allowed no one to abuse the crew, and especially objected to the
use of profane language, which he condemned as the most foolish
of practices. He appointed the day for me to come on board and I
left him pleased with my success, but with a lurking suspicion that
my fair-talking captain might prove to belong to the class known as
"shore-saints and sea-devils." The owner, however, was one of the
best men living, a noble philanthropist, and a vice-president of the
Seamen's Friend Society. I therefore felt some assurance that his
ship would have a respectable captain and be well conducted.
At six o'clock, one dark morning in the end of November, my fond
father bade me farewell at the door, as I left my pleasant home and
its gentle occupants, and trudged to East Boston, in a storm of sleet,
to enter upon a sphere and mingle with associates so contrasted,
that I needed no other illustration, for the next few months, to
impress upon my mind the two extremes of the future life.
The ship was bound to Richmond, Virginia, in ballast, there to load a
cargo of tobacco for the Mediterranean. In the forenoon, a negro
crew of fourteen men and two boys came on board. They were
mostly fine "strapping" fellows, with bright eyes and shining
"ivories," and as we proceeded down the bay they made the decks
ring with their songs; the main-topsail going to the mast-head to the
tune of "Come down you bunch o' roses, come down," and the fore-
topsail halyards answering to the strong pulls following the
sentiment:
"Sally Brown's a bright Mulatto,
She drinks rum and chews tobacco."
A man who was loosing the mizzen-top-gallant-sail was heard to
utter some profane exclamations over the bunt gasket, which was
made fast with a knot that resisted all his efforts at untying, being
what sailors call "an anti-gallican hitch." As I have mentioned, Capt.
Streeter had remarked a few days before that he allowed no profane
language on board of his ship, and I wondered if he would take any
notice of this; but I did not wait long before having my curiosity
satisfied. The same thought probably came to the captain's mind, for
he stepped to where he could get a good look at the man, and then
began: "Button your lip up, or I'll knock spots out of you. I don't
allow swearing on board of this boat;" with more to the same effect,
accompanied by several profane epithets. It was evident that the
captain's fluency of speech was not limited to polite conversation,
and his consistency was explained by his remarking, at a future
time, that his rule on board ship was, "do as I order, not as I do."
The Pilot left at Boston Light. All hands were busily employed putting
things to rights, for a ship is seldom in order except when at sea.
There, men are constantly laboring to keep everything "ship-shape"
and tidy, and the moment the vessel is moored at the wharf, crew
and officers generally go over the side, stevedores, riggers and
carpenters take possession, and the decks are in a turmoil until she
is again out of the range of visitors.
It surprised me to see the captain interesting himself in all the work,
for in previous voyages its execution had been left entirely to the
officers. While the mate was securing the anchors, the captain
visited the top-gallant forecastle and offered suggestions, which the
high-spirited first officer treated with a contemptuous silence. The
black eyes shone with suppressed rage, and their owner transferred
his interference to the second mate's labors, which were being
employed in putting on chafing-gear. He soon worked this officer
into such a flurry, that he hardly knew whether he stood on his head
or his heels, and then after putting a stop to a job the carpenter had
undertaken, and peeping into the cook's boilers to see how much
beef they contained, to the delight of all, he disappeared into the
cabin, but in a few minutes his loud tones showed that the steward
was the object of his attentions.
In the evening, after the watches were chosen, the captain joined
the officers on deck and talked familiarly with us, illustrating his
remarks by anecdotes and comparisons more amusing than refined.
We were obliged to confess to each other that he was a very
agreeable man in private, and for a time forgot all the mental
imprecations we had bestowed on him during the day, on account of
his interference with the work.
The mate and second mate had a talk by themselves concerning
their duties, and the second mate, while expatiating upon his own
good qualifications, put his hand in his pocket and pulling out a pair
of brass knuckles put them upon his hand. Holding his fist up, he
said: "I always carry my tools with me, and if you ever want any
work done, you have only to say the word, and you'll find me on
hand like Day and Martin's blacking."
"I don't want you to let me see those things again, while you're on
board of this ship," said the mate.
"Why so; do you intend to let those sailors play Isaac and Josh with
you?"
"No," said the mate, "but when I can't keep men in order, without
using such weapons as that, I'll give up to some one who can. I
never knew a man yet who carried such things but he proved to be
a coward at heart."
"No man can call me a coward," replied the second mate in an angry
tone.
"Well," said the mate, "I hope you are not one, but I shall think
better of you if I hear nothing more about brass knuckles."
This was not a very pleasant opening of acquaintance, and both
parties took at the outset a dislike to each other.
I gained from each of them a brief account of their antecedents.
Mr. Morrison, the first mate, was a Scotchman by birth, about forty-
two years of age. He had been captain of English vessels, but having
met with misfortunes, concerning which he was very reticent, he had
begun to seek his fortune in the American merchant service. He was
a short, thick-set man, with a ruddy complexion and a cast of
countenance expressing courage and determination. His bearing was
significant of "Scotch pride." He was a man of much intelligence and
had received a good education.
Mr. Howard, the second mate, hailed from the State of Maine. He
was of medium height and well built, but had a brutal look and
seemed ordinary in intelligence. He frankly confided to me the
immediate occasion of his shipping in the "Dublin."
"Last voyage I was second mate of the 'Minerva.' We had a nigger
crew and used 'em pretty rough I must say; but I had 'em in such
good discipline that one day I got mad with a 'moke' about
something and I told him to lay his head down on the hatch for I
was going to chop it off. He did just as I told him, and though he
thought I was going to kill him, he didn't dare to move or say his
soul was his own. That's what I call good discipline.
"We kept them under well enough at sea, but when we got into Rio
Janeiro, what did the scamps do but set fire to the ship, and burn
her up; and two days after a gang of 'em caught me one evening in
the street, and gave me such a pounding that I couldn't see out of
my eyes for a fortnight. I believe they'd have killed me if the police
hadn't come along and rescued me. I vowed then I would sail just
once more with a nigger crew, and from what I hear of this captain,
I think he's just the man that'll suit me."
The "Dublin" had a fair start. In three days we sighted the Capes of
Virginia and in two more worked up the James River to City Point.
City Point then consisted of about twenty dwelling houses beside the
negroes' cabins, and had wharves at which the vessels lay while
receiving their cargoes of tobacco, which came to them in lighters
from the city of Richmond, about thirty miles above, the shallowness
of the river preventing anything but vessels of light draft from
proceeding there. The tobacco was packed in large hogsheads,
weighing from one thousand to eighteen hundred pounds, and as
the crew hoisted them in they kept up a song from morning till
night. Negro stevedores from the shore stowed them in the hold,
and the captain spent almost all his time down there, watching that
they saved all the room possible, frequently making them "break
out" again, to the great disgust of the negroes. I heard one of them
saying to the others: "I nebber see such a man as dis cap'n afore;
he tinks he knows eberyting and nobody else don't know nuffin."
There was of course nothing here to interest us beyond receiving
our tobacco, and when the ship was loaded to sixteen feet draft she
dropped down the river ten miles, into deeper water, and there
completed her cargo.
On a fine clear day in the end of December, we left the shore of
Virginia astern and steered for the Straits of Gibraltar. Fresh and
favorable winds prevailed for several days and we made good
progress on our voyage.
One evening the captain in a confidential mood read us some
extracts from the owner's letter of instructions, and was particularly
merry over the latter part of it, which read: "You will distribute to the
men the books and tracts which are supplied. You will endeavor to
suppress all vice and immorality on board of your vessel and use
your best efforts to promote the welfare of your crew."
The inmates of the ship now felt acquainted with each other, and as
a general thing their good opinions were very much modified.
Capt. Streeter having no taste for reading, and being a man of
energetic and active temperament, could not content himself in his
cabin, and was almost constantly on deck roaming about the ship,
criticizing every job of work, "in every body's mess and nobody's
watch."
When bracing yards, making or taking in sail, he would stand on top
of the house, and accompany his orders with volleys of oaths,
provided things were not done exactly to his mind. If the crew did
not move quite actively enough, and nothing in this way would suit
him but the "clean jump," every blackguard epithet that his fluent
tongue and inventive brain could command was heaped upon them:
Scoundrels, black scorpions, and names too filthy for utterance were
their common titles at such times, and when the men and officers
did so well that he could not find a point to censure, he seemed
rather disappointed at losing an opportunity for this favorite
employment. Sailors call such a man, "a blower."
At night no one was allowed to sit down on deck, and though no
work was to be done, the sailors had to keep on their legs. Such
strict rules of course gave the officers a good deal of disagreeable
work. From eight to twelve at night the men would have to walk the
deck, unless engaged in working ship, and when at four o'clock, a.m.,
they were roused out, after four hours slumber, they could not
always resist the temptation to sit down on a spar, or lean over a
water-cask. In spite of their efforts to keep awake, their heads would
drop upon their arms and they would fall asleep.
If anyone wishes to experience something which in his recollections
will serve as a synonym for misery, let him sail in such a ship and
stand the morning watch. In the hour from four to five as he
stumbles about the deck, endeavoring to drive away the drowsiness
that weighs down his eyelids, he will feel a wretchedness, which,
unless he is a very unfortunate man, will seldom, if ever, be
surpassed during his life.
The mate failed to carry out these orders very strictly, as he knew it
could only be done by harsh measures; for though his fiery temper
often led him to strike a blow at some unlucky sailor, he despised all
premeditated schemes to abuse or oppress them. Besides this, he
thought he saw through the captain's character. He imagined that he
was anxious to gain for the "Dublin" the reputation of being a "hard"
ship, provided his officers would do all the necessary "dirty work,"
but was unwilling to expose himself to the present dangers of
fighting, or the future disgrace of lawsuits. Their relations to each
other were not very pleasant, for the mate was jealous of the
captain's interference with his work, and the captain, perceiving his
state of mind, attempted to retaliate by little acts of oppression, of
which one will be sufficient to show the spirit.
The mate's room was very small. His only convenience for writing up
his log book was at a narrow standing desk, where he was too much
cramped to do it neatly.
At the beginning of the passage he sat down at the table in the
forward cabin to perform this part of his duty, and the captain
coming from his spacious after-cabin found him there at work. Upon
seeing him he drew himself up, and in a pompous way said: "Mr.
Morrison, I want you to understand that my cabin table isn't a
writing desk for officers."
"Oh, indeed," said the mate. "I've always been accustomed to have
the use of it even for my private writing, and I had no idea you
would object to my writing the ship's log here."
"You must learn you ai'n't aboard one of your lime-juice ships now,"
was the courteous response, and the mate retired to his room, his
Scotch pride and temper almost overcoming his desire to respect the
captain.
But the second mate was a man after the captain's own heart. It
was only necessary to show him the way to the captain's good
graces, and his subservience joined to his own brutal passions made
him an earnest disciple.
The crew were a pretty independent and saucy set of negroes, and
required a strict hand to keep them under. From the very first there
had been almost daily little difficulties, and at one time at City Point
a general knock-down was only prevented by the mate's interfering
between the second mate and a sailor, to the great wrath of the
former.
A few days after leaving the Chesapeake, Mr. Howard was going
around the deck at about half-past four in the morning, and found a
man called Brooks sitting down and nodding. He awakened him very
suddenly by raising him up by the ears, and then set the whole
watch to work bracing the yards "in" a little. The men were sleepy,
and cross at this "humbugging," for they knew the wind had not
altered at all, and this was merely a "work up job." They were not
very prompt with their Aye, aye, sir.
"Haul in the top-gallant-brace" said the officer.
No answer followed, but he saw the order was obeyed.
"Belay!"
Still no answer.
"Sing out," said he; "if you don't open your gills I'll slaughter you.
Haul in the royal-brace!"
No answer.
He turned in a rage and catching hold of Brooks, who was nearest
him, gave him a blow with his brass knuckles that would have
unsettled any ordinary head. But the darkey's skull was not very
sensitive, and he at once drew his sheath-knife, and stabbed Howard
in the abdomen. He had on thick clothes, and the knife after cutting
through them inflicted only a small flesh wound. Howard was rather
frightened by this episode, and not knowing how badly he was cut,
upon seeing the other men seize handspikes and belaying pins ready
to join Brooks, in case of any further attack, he thought it best to
retreat. After breakfast he reported the case to the captain, who
sent for Brooks to come into the cabin, where he took his position
with a pistol and a fathom of ratline stuff. Having shut the door, so
that there should be no witnesses, he made the man take off his
shirt; and then flogged him till the blood flowed down his back, and
the man's cries and promises made him desist.
The captain's prompt espousal of the second mate's cause showed
that he would stand by his officers, and it had the effect of making
the crew more respectful and careful.
Being the third mate, I was of course in the mate's watch; my duty
was to follow up the execution of the mate's orders, and look after
the little details of work. I must know the place for everything and
see that it was in its place. When the decks were cleared up at
night, if the mate in his inspection spied a stray marline-spike or
serving-board, it was the third mate who had to answer for it. If a
sailor wanted spunyarn or seizing-stuff to work with, it was the third
mate who must know where to find it and run and get it, or if the
lockers were not in order or the tar-barrel fetched adrift he was the
first looked at for blame. In his turn of course he could growl at the
sailors, but that was rather poor satisfaction, and he had not filled
his office many days before he came to the conclusion that it was a
most thankless billet, and that a third mate's portion contained "a
larger share of kicks than of coppers." I was only nineteen years old.
The sailors looked upon me as a youngster, and were not inclined to
be particularly respectful, thinking I wouldn't dare to use force with
them.
The captain watched me very closely, wishing to train me up in the
way I should go, and many a harsh-sounding order or rebuke I got
from him on deck, all the more galling because given in the presence
of the men. But personally the captain seemed favorably inclined
toward me, or else he feared lest I might make a report of his
doings to the owner, and thus sought frequent opportunities to talk
with me and smooth over my ruffled feelings. It is not customary for
a captain to have any conversation with a third mate, and I was not
quite sure as to his motive, though I leaned to the latter opinion,
judging from the tenor of all his stories, talk and advice, which was
to the sole end of discipline, or, perhaps more exactly, of fighting
sailors. In consulting with the mate as to this he gave me a decided
opinion. "All the old man wants," said he, "is to have you tarred with
the same brush as himself, and then he thinks you wouldn't injure
him ashore, for you know it doesn't do for the pot to call the kettle
black."
One day we were reefing the mizzen-topsail and I was astride of the
yard-arm hauling out the weather earing. The captain saw from the
deck that the men had not gathered up all the slack sail on top of
the yard, before tying the reef-points; and he at once set up a roar
of mingled oaths and orders, which, with a storm howling past my
ears produced a bewildering effect. With some difficulty I divined the
pith of his remarks, and gave the necessary directions; but this was
not enough for the captain, who sang out to me, "What's the use of
sitting there and talking to them, get up on the yard and kick their
heads off." A good deal more followed, but I was too angry to hear
anything else and paid no attention.
The captain saw that I was rather out of sorts for the rest of the day,
and in the dog-watch came up to me as I was leaning against the
booby-hatch and began in his pleasant fluent way to tell me a story.
"You never met Mr. Jones of Baltimore did you?"
"No sir, I never did."
"Well, he was my second mate, when I had the ship 'Daphne' in the
China trade."
I had heard from good authority on shore that the "Dublin" was the
only ship Capt. Streeter had ever commanded, and since being at
sea with him I had learned that Mr. Jones was his ideal officer, and
whenever he wished to give a hint to his present mates upon points
where he felt he could not command, his favorite and usual method
was to convey it in a story about Mr. Jones, and Mr. Jones' name had
already become a by-word among the officers. I knew what was
coming and prepared to receive instructions.
"Mr. Jones," continued the captain, "never went aloft to reef topsails
without having a belaying pin stuck into the leg of his boot. He used
to take his stand in the slings of the yard, and if the sail wasn't
picked up pretty lively, before you could count twenty he would have
been out on both yard-arms, and hit every man a tap on the head
that made 'em take hold like young tigers. Then when the sail was
reefed he'd sing out, 'lay down,' and as every man got into the
rigging, if he wasn't mighty spry, he'd get helped along with a kick,
and then he followed the last man down and jumped on his head
and shoulders, if he could overtake him. I tell you it was fun to see
them scatter when he said 'lay down.' They would come sliding
down the backstays like a parcel of monkeys, and once a Dutchman,
who happened to be the last man, and saw the second mate's boots
just above his head, got so frightened that he jumped down from
half way up the main-rigging and broke his leg. I had to scold Jones
though a little for that, as the galoot was laid up the rest of the
voyage."
"I should think that was rather poor economy," said I, "to lose a
man's labor for several months, for the sake of gaining a few
seconds time in getting down from aloft."
"It paid though, after all," answered the captain, "for Jones could
get as much work out of six men as some could out of a dozen. It's
worse economy to be too humane with sailors."
"If that is being a smart officer I hardly think I shall become one,"
said I.
"I'll tell you what it is, you'll never make one unless you give up
some of your conscientious scruples. I must say you do very well
about your work, but you're too humane a man to go to sea, and if
you want to get along in this profession you've got to leave your nice
principles on shore. There's no religion off soundings. The captain of
a ship has got to be a liar, a cheat, a swearer, a fighter and a tyrant;
in fact, if you mean to be a good mate or a good captain you've got
to be a rascal."
"If good principles are good for anything they are good for
everything," I replied, "and if what you say is true, either this is a
profession no one ought to follow or else religion is a sham and
ought to be hove overboard entirely. A good God would never have
imposed laws upon us which would interfere with our necessary
occupations, and I don't believe he meant the Golden Rule to be
confined to the shore."
"That all sounds very fine," said the captain, "and perhaps you'd
better knock off going to sea and set up for a parson. But you mark
my words, if you go to sea, you'll have to give up your principles
sooner or later, and you may as well make up your mind to it now.
I've seen a good many that started as fair as you've done, but it
didn't last long. But here we've got proof right alongside of us. Just
look at Mr. Howard's watch there. Every time he opens his mouth
you see them piling along like greased lightning, and he gets half a
dozen answers for every order. But your men don't answer you half
the time, and they move slower than real estate in Chelsea.
"Now if you saw a man walking alongside of a high brick wall, and
you politely asked him to step along a little faster, he'd stop and look
at you; but if you told him the brick wall was tumbling down over his
head you'd see how quick he'd make the dust fly. It's just so with a
sailor, if you are civil to him he won't care a curse for you, but if you
let him know there's something coming down on his head he'll move
quick and respect you. A man didn't answer Mr. Jones once, and he
just picked up the carpenter's caulking mallet and hit him over the
head. He never had to speak twice to him after that."
Finding the captain had got back to his favorite Mr. Jones, I thought
it was of no use to prolong the talk, and it being my watch below I
went to my room. Sitting down upon my chest I thought of the
contrast between the captain's instructions and the teachings of
home, and wondered if I must abandon the latter. It was very
evident that there was not the strict discipline in the mate's watch
that there was in the second mate's, and the captain's comparisons
galled me; but it seemed to me that the discipline in our watch was
good enough; the men did their duty well and were respectful,
except that they were not always particular about answering and
sometimes walked along the deck to ordinary work, whereas the
second mate's men always ran, knowing that a belaying pin or stick
of fire-wood would be hurled after them if they didn't. I felt the
captain was right in saying that such strict discipline could not be
maintained, except by working on the fears of the men, but the
question with me was whether it was necessary to be so strict. Our
men in a squall, or gale of wind, would be just as smart as the
second mate's. It was only in ordinary and comparatively
unimportant work that they were at all behind-hand, and I made up
my mind that a system which necessarily required inhumanity and a
sacrifice of honorable principles must be wrong, and I would have as
little to do with it as possible. Opening my chest I took out a bundle
of letters and selected one from my father. It was an answer to one
I had written from City Point, in which I spoke of the severe
discipline which was maintained on board the "Dublin," and the
course which was required of the officers, and asked for advice.
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookgate.com

More Related Content

PDF
TinyOS programming 1st Edition Philip Levis
PDF
TinyOS programming 1st Edition Philip Levis
PDF
(Ebook) TinyOS programming by Philip Levis, David Gay ISBN 9780521896061, 052...
PPTX
PDF
Tos tutorial
PDF
Arduino bộ vi điều khiển cho tất cả chúng ta part 1
PDF
T2: What the Second Generation Holds
TinyOS programming 1st Edition Philip Levis
TinyOS programming 1st Edition Philip Levis
(Ebook) TinyOS programming by Philip Levis, David Gay ISBN 9780521896061, 052...
Tos tutorial
Arduino bộ vi điều khiển cho tất cả chúng ta part 1
T2: What the Second Generation Holds

Similar to TinyOS programming 1st Edition Philip Levis (20)

PDF
Programming Embedded Systems With C And Gnu Development Tools 2nd Edition 2nd...
PDF
EEEM048_Lecture5_Software platforms and services .pdf
PDF
Tinyos programming
PPT
Tiny os
PPT
TinyOS 2.1 tutorial at IPSN 2009
PDF
nesC Part 1 (1).pdfbhhhhjjjjjjjjjjjjjjjjjkk
PDF
Nesc tutorial
PDF
Discovering st32
PPTX
IOT beginnners
PPTX
IOT beginnners
PPT
Embedded systems
PPT
Lecture 5: Software platforms and services
PDF
Embedded Software For The Iot 3rd Edition Klaus Elk
PDF
Intro to embedded systems programming
PPTX
Embedded system and IoT,Embeded systems.pptx
PDF
Embedded Software for the IoT 3rd Edition Klaus Elk
PPT
0903 1
PDF
Embedded Systems Architecture Programming and Design 2nd Edition Raj Kamal
PDF
What is arduino
PPT
L26.B.FA20.ppt
Programming Embedded Systems With C And Gnu Development Tools 2nd Edition 2nd...
EEEM048_Lecture5_Software platforms and services .pdf
Tinyos programming
Tiny os
TinyOS 2.1 tutorial at IPSN 2009
nesC Part 1 (1).pdfbhhhhjjjjjjjjjjjjjjjjjkk
Nesc tutorial
Discovering st32
IOT beginnners
IOT beginnners
Embedded systems
Lecture 5: Software platforms and services
Embedded Software For The Iot 3rd Edition Klaus Elk
Intro to embedded systems programming
Embedded system and IoT,Embeded systems.pptx
Embedded Software for the IoT 3rd Edition Klaus Elk
0903 1
Embedded Systems Architecture Programming and Design 2nd Edition Raj Kamal
What is arduino
L26.B.FA20.ppt
Ad

Recently uploaded (20)

PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Business Ethics Teaching Materials for college
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
Complications of Minimal Access Surgery at WLH
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Pre independence Education in Inndia.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Classroom Observation Tools for Teachers
PPTX
Pharma ospi slides which help in ospi learning
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
Microbial disease of the cardiovascular and lymphatic systems
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Business Ethics Teaching Materials for college
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
FourierSeries-QuestionsWithAnswers(Part-A).pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
VCE English Exam - Section C Student Revision Booklet
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Complications of Minimal Access Surgery at WLH
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Pre independence Education in Inndia.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
TR - Agricultural Crops Production NC III.pdf
Classroom Observation Tools for Teachers
Pharma ospi slides which help in ospi learning
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PPH.pptx obstetrics and gynecology in nursing
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Week 4 Term 3 Study Techniques revisited.pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
Ad

TinyOS programming 1st Edition Philip Levis

  • 1. TinyOS programming 1st Edition Philip Levis pdf download https://ebookgate.com/product/tinyos-programming-1st-edition- philip-levis/ Get Instant Ebook Downloads – Browse at https://ebookgate.com
  • 2. Instant digital products (PDF, ePub, MOBI) available Download now and explore formats that suit you... Sheep 1st Edition Philip Armstrong https://ebookgate.com/product/sheep-1st-edition-philip-armstrong/ The Collected Poems of Philip Lamantia First Edition Philip Lamantia https://ebookgate.com/product/the-collected-poems-of-philip- lamantia-first-edition-philip-lamantia/ Dear Zoe 1st Edition Edition Philip Beard https://ebookgate.com/product/dear-zoe-1st-edition-edition- philip-beard/ Philip Kaufman 1st Edition Edition Annette Insdorf https://ebookgate.com/product/philip-kaufman-1st-edition-edition- annette-insdorf/
  • 3. Alec Wilder 1st Edition Edition Philip Lambert https://ebookgate.com/product/alec-wilder-1st-edition-edition- philip-lambert/ Valode Pistre Architects 1st Edition Philip Jodidio https://ebookgate.com/product/valode-pistre-architects-1st- edition-philip-jodidio/ Computer Programming 1st Edition E. Balagurusamy https://ebookgate.com/product/computer-programming-1st-edition-e- balagurusamy/ Carbon Programming 1st Edition Kevin Bricknell https://ebookgate.com/product/carbon-programming-1st-edition- kevin-bricknell/ Programming Clojure 1st Edition Stuart Halloway https://ebookgate.com/product/programming-clojure-1st-edition- stuart-halloway/
  • 6. TinyOS Programming Do you need to know how to write systems, services, and applications using the TinyOS operating system? Learn how to write nesC code and efficient applications with this indispensable guide to TinyOS programming. Detailed examples show you how to write TinyOS code in full, from basic applications right up to new low-level systems and high-performance applications. Two leading figures in the development of TinyOS also explain the reasons behind many of the design decisions made and explain for the first time how nesC relates to and differs from other C dialects. Handy features such as a library of software design patterns, programming hints and tips, end-of-chapter exercises, and an appendix summarizing the basic application-level TinyOS APIs make this the ultimate guide to TinyOS for embedded systems programmers, developers, designers, and graduate students. Philip Levis is Assistant Professor of Computer Science and Electrical Engineering at Stanford University. A Fellow of the Microsoft Research Faculty, he is also Chair of the TinyOS Core Working Group and a Member of the TinyOS Network Protocol (net2), Simulation (sim), and Documentation (doc) Working Groups. David Gay joined Intel Research in Berkeley in 2001, where he has been a designer and the principal implementer of the nesC language, the C dialect used to implement the TinyOS sensor network operating system, and its applications. He has a diploma in Computer Science from the Swiss Federal Institute of Technology in Lausanne and a Ph.D. from the University of California, Berkeley.
  • 8. TinyOS Programming PHILIP LEVIS Stanford University and DAVID GAY Intel Research
  • 9. CAMBRIDGE UNIVERSITY PRESS Cambridge, New York, Melbourne, Madrid, Cape Town, Singapore, São Paulo Cambridge University Press The Edinburgh Building, Cambridge CB2 8RU, UK First published in print format ISBN-13 978-0-521-89606-1 ISBN-13 978-0-511-50730-4 © Cambridge University Press 2009 2009 Information on this title: www.cambridge.org/9780521896061 This publication is in copyright. Subject to statutory exception and to the provision of relevant collective licensing agreements, no reproduction of any part may take place without the written permission of Cambridge University Press. Cambridge University Press has no responsibility for the persistence or accuracy of urls for external or third-party internet websites referred to in this publication, and does not guarantee that any content on such websites is, or will remain, accurate or appropriate. Published in the United States of America by Cambridge University Press, New York www.cambridge.org eBook (EBL) paperback
  • 10. Contents List of Code examples page xi Preface xvii Acknowledgements xix Programming hints, condensed xxi Part I TinyOS and nesC 1 1 Introduction 3 1.1 Networked, embedded sensors 3 1.1.1 Anatomy of a sensor node (mote) 4 1.2 TinyOS 5 1.2.1 What TinyOS provides 6 1.3 Example application 7 1.4 Compiling and installing applications 8 1.5 The rest of this book 8 2 Names and program structure 10 2.1 Hello World! 10 2.2 Essential differences: components, interfaces, and wiring 13 2.3 Wiring and callbacks 15 2.4 Summary 16 Part II Basic programming 19 3 Components and interfaces 21 3.1 Component signatures 21 3.1.1 Visualizing components 22 3.1.2 The “as” keyword and clustering interfaces 23 3.1.3 Clustering interfaces 24 3.2 Interfaces 24 3.2.1 Generic interfaces 27 3.2.2 Bidirectional interfaces 28
  • 11. vi Contents 3.3 Component implementations 29 3.3.1 Modules 30 3.3.2 A basic configuration 31 3.3.3 Module variables 32 3.3.4 Generic components 33 3.4 Split-phase interfaces 34 3.4.1 Read 36 3.4.2 Send 36 3.5 Module memory allocation, avoiding recursion, and other details 36 3.5.1 Memory ownership and split-phase calls 38 3.5.2 Constants and saving memory 41 3.5.3 Platform-independent types 42 3.5.4 Global names 44 3.5.5 nesC and the C preprocessor 46 3.5.6 C libraries 47 3.6 Exercises 48 4 Configurations and wiring 49 4.1 Configurations 50 4.1.1 The −> and <− operators 51 4.1.2 The = operator 52 4.1.3 Namespace management 53 4.1.4 Wiring rules 54 4.1.5 Wiring shortcuts 56 4.2 Building abstractions 57 4.2.1 Component naming 58 4.2.2 Component initialization 59 4.3 Component layering 60 4.3.1 Extensibility 61 4.3.2 Hardware specificity 61 4.4 Multiple wirings 63 4.4.1 Fan-in and fan-out 64 4.4.2 Uses of multiple wiring 65 4.4.3 Combine functions 66 4.5 Generics versus singletons 68 4.5.1 Generic components, revisited 68 4.5.2 Singleton components, revisited 70 4.6 Exercises 70 5 Execution model 71 5.1 Overview 71 5.2 Tasks 72 5.2.1 Task timing 74
  • 12. Contents vii 5.2.2 Timing and event handlers 75 5.3 Tasks and split-phase calls 75 5.3.1 Hardware versus software 75 5.3.2 Tasks and call loops 76 5.4 Exercises 78 6 Applications 79 6.1 The basics: timing, LEDs, and booting 79 6.1.1 Deadline-based timing 81 6.1.2 Wiring AntiTheftC 83 6.2 Sensing 83 6.2.1 Simple sampling 84 6.2.2 Sensor components 85 6.2.3 Sensor values, calibration 86 6.2.4 Stream sampling 87 6.3 Single-hop networking 89 6.3.1 Sending packets 90 6.3.2 Receiving packets 93 6.3.3 Selecting a communication stack 94 6.4 Multi-hop networking: collection, dissemination, and base stations 95 6.4.1 Collection 96 6.4.2 Dissemination 97 6.4.3 Wiring collection and dissemination 97 6.4.4 Base station for collection and dissemination 98 6.5 Storage 101 6.5.1 Volumes 102 6.5.2 Configuration data 103 6.5.3 Block and Log storage 105 6.6 Exercises 111 7 Mote-PC communication 112 7.1 Basics 112 7.1.1 Serial communication stack 113 7.2 Using mig 114 7.2.1 Sending and receiving mig-generated packets 116 7.3 Using ncg 118 7.4 Packet sources 119 7.5 Example: simple reliable transmission 120 7.5.1 Reliable transmission protocol 121 7.5.2 Reliable transmission in Java 121 7.5.3 Reimplementing TestSerial 125 7.6 Exercises 125
  • 13. viii Contents Part III Advanced programming 127 8 Advanced components 129 8.1 Generic components review 129 8.2 Writing generic modules 131 8.2.1 Type arguments 132 8.2.2 Abstract data types as generics 133 8.2.3 ADTs in TinyOS 1.x 134 8.3 Parameterized interfaces 135 8.3.1 Parameterized interfaces and configurations 137 8.3.2 Parameterized interfaces and modules 139 8.3.3 Defaults 141 8.4 Attributes 142 8.5 Exercises 144 9 Advanced wiring 145 9.1 unique() and uniqueCount() 145 9.1.1 unique 146 9.1.2 uniqueCount 147 9.1.3 Example: HilTimerMilliC and VirtualizeTimerC 147 9.2 Generic configurations 150 9.2.1 TimerMilliC 150 9.2.2 CC2420SpiC 152 9.2.3 AMSenderC 156 9.2.4 BlockStorageC 160 9.3 Reusable component libraries 162 9.4 Exercises 165 10 Design patterns 166 10.1 Behavioral: Dispatcher 166 10.2 Structural: Service Instance 170 10.3 Namespace: Keyspace 174 10.4 Namespace: Keymap 177 10.5 Structural: Placeholder 180 10.6 Structural: Facade 183 10.7 Behavioral: Decorator 186 10.8 Behavioral: Adapter 189 11 Concurrency 192 11.1 Asynchronous code 192 11.1.1 The async keyword 192 11.1.2 The cost of async 193 11.1.3 Atomic statements and the atomic keyword 195
  • 14. Contents ix 11.1.4 Managing state transitions 197 11.1.5 Example: CC2420ControlP 197 11.1.6 Tasks, revisited 199 11.2 Power locks 200 11.2.1 Example lock need: link-layer acknowledgements 200 11.2.2 Split-phase locks 201 11.2.3 Lock internals 202 11.2.4 Energy management 203 11.2.5 Hardware configuration 204 11.2.6 Example: MSP430 USART 204 11.2.7 Power lock library 205 11.3 Exercises 205 12 Device drivers and the hardware abstraction architecture (HAA) 206 12.1 Portability and the hardware abstraction architecture 206 12.1.1 Examples 208 12.1.2 Portability 210 12.2 Device drivers 210 12.2.1 Access control 211 12.2.2 Access control examples 212 12.2.3 Power management 215 12.2.4 Microcontroller power management 218 12.3 Fitting in to the HAA 219 13 Advanced application: SoundLocalizer 221 13.1 SoundLocalizer design 221 13.1.1 Time synchronization 222 13.1.2 Implementing SoundLocalizer in TinyOS 223 13.2 SynchronizerC 225 13.3 DetectorC 230 13.4 MicrophoneC 233 13.5 Wrap-up 237 Part IV Appendix and references 239 A TinyOS APIs 241 A.1 Booting 241 A.2 Communication 241 A.2.1 Single-hop 242 A.2.2 Multi-hop collection 243 A.2.3 Multi-hop dissemination 244 A.2.4 Binary reprogramming 245 A.3 Time 245 A.4 Sensing 245
  • 15. x Contents A.5 Storage 246 A.6 Data structures 247 A.6.1 BitVectorC 247 A.6.2 QueueC 247 A.6.3 BigQueueC 248 A.6.4 PoolC 248 A.6.5 StateC 249 A.7 Utilities 249 A.7.1 Random numbers 249 A.7.2 Leds 249 A.7.3 Cyclic redundancy checks 250 A.7.4 Printf 250 A.8 Low power 251 References 252 Index 254
  • 16. Code examples 2.1 Powerup in C page 10 2.2 PowerupC module in nesC 11 2.3 Simple nesC interfaces 11 2.4 PowerupAppC configuration in nesC 12 2.5 Powerup with blinking LED in C 15 2.6 Powerup with blinking LED in nesC (slightly simplified) 15 2.7 Powerup with blinking LED configuration (slightly simplified) 16 3.1 The signature and implementation blocks 21 3.2 Signatures of PowerupC and LedsC 22 3.3 MainC’s signature 22 3.4 The LedsP module 23 3.5 PowerupC and an alternative signature 24 3.6 Interface declarations for Leds and Boot 25 3.7 The Init and Boot interfaces 25 3.8 Signatures of MainC and PowerupC 26 3.9 The Queue interface 27 3.10 Using a queue of 32-bit integers 27 3.11 Providing a 16-bit or a 32-bit queue 27 3.12 The Notify interface 28 3.13 UserButtonC 28 3.14 Simplified Timer interface showing three commands and one event 29 3.15 PowerupC module code 30 3.16 The module PowerupToggleC 30 3.17 The PowerupToggleAppC configuration 31 3.18 Example uses of the components keyword 31 3.19 The Get interface 32 3.20 A self-incrementing counter 32 3.21 Generic module SineSensorC and generic configuration TimerMilliC 33 3.22 Instantiating a generic component 34 3.23 Signature of BitVectorC 34 3.24 QueueC signature 34 3.25 The Read interface 36 3.26 The split-phase Send interface 36 3.27 The Send interface 38
  • 17. xii List of code examples 3.28 The Receive interface 39 3.29 The signature of PoolC 41 3.30 CC2420 packet header 42 3.31 The dreaded “packed” attribute in the 1.x MintRoute library 43 3.32 The CC2420 header 44 3.33 TinyError.h, a typical nesC header file 45 3.34 Including a header file in a component 45 3.35 Indirectly including a header file 46 3.36 Fancy.nc: C preprocessor example 46 3.37 FancyModule.nc: C preprocessor pitfalls 47 3.38 Fancy.h: the reliable way to use C preprocessor symbols 47 3.39 Using a C library function 47 4.1 Signature of part of the CC1000 radio stack 49 4.2 The PowerupToggleAppC configuration revisited 51 4.3 C code generated from the PowerupToggleAppC configuration 51 4.4 The LedsC configuration 52 4.5 CC2420ReceiveC’s use of the as keyword 53 4.6 Naming generic component instances 54 4.7 MainC and LedsP 55 4.8 Valid alternate of PowerupToggleAppC 55 4.9 Invalid alternate of PowerupToggleAppC 55 4.10 LedsC revisited 56 4.11 BlinkC signature 56 4.12 The RandomC configuration 57 4.13 The RandomMlcgC signature 58 4.14 Seed initialization in RandomMlcgP 59 4.15 ActiveMessageC for the CC2420 61 4.16 The signature of CC2420ActiveMessageC 62 4.17 Fan-out on CC2420TransmitC’s Init 63 4.18 StdControl and SplitControl initialization interfaces 64 4.19 Why the metaphor of “wires” is only a metaphor 65 4.20 The combine function for error_t 66 4.21 Fan-out on SoftwareInit 67 4.22 Resulting code from fan-out on SoftwareInit 67 4.23 AMSenderC signature 68 4.24 RadioCountToLedsAppC 68 4.25 PoolC 69 4.26 Exposing a generic component instance as a singleton 70 5.1 The main TinyOS scheduling loop from SchedulerBasicP.nc 72 5.2 A troublesome implementation of a magnetometer sensor 76 5.3 Signal handler that can lead to an infinite loop 77 5.4 An improved implementation of FilterMagC 77 6.1 Anti-theft: simple flashing LED 80 6.2 The Leds interface 80
  • 18. List of code examples xiii 6.3 The Boot interface 81 6.4 The full Timer interface 81 6.5 WarningTimer.fired with drift problem fixed 82 6.6 Anti-Theft: application-level configuration 83 6.7 The Read interface 84 6.8 Anti-theft: detecting dark conditions 84 6.9 Anti-Theft: wiring to light sensor 86 6.10 ReadStream Interface 87 6.11 Anti-theft: detecting movement 88 6.12 The AMSend interface 90 6.13 Anti-Theft: reporting theft over the radio 91 6.14 The SplitControl interface 92 6.15 The Receive interface 93 6.16 Anti-Theft: changing settings 93 6.17 Serial vs Radio-based AM components 94 6.18 The Send interface 96 6.19 Anti-Theft: reporting theft over a collection tree 96 6.20 DisseminationValue interface 97 6.21 Anti-Theft: settings via a dissemination tree 97 6.22 The StdControl interface 97 6.23 The DisseminationUpdate interface 99 6.24 AntiTheft base station code: disseminating settings 99 6.25 The RootControl interface 100 6.26 AntiTheft base station code: reporting thefts 101 6.27 AntiTheft base station wiring 101 6.28 ConfigStorageC signature 102 6.29 Mount interface for storage volumes 103 6.30 ConfigStorage interface 103 6.31 Anti-Theft: reading settings at boot time 104 6.32 Anti-Theft: saving configuration data 105 6.33 BlockStorageC signature 106 6.34 The BlockWrite interface 106 6.35 Simultaneously sampling and storing to flash (most error checking omitted) 108 6.36 The BlockRead interface 108 6.37 LogStorageC signature 108 6.38 The LogWrite interface 109 6.39 The LogWrite interface 110 6.40 The LogRead interface 111 7.1 Serial AM Packet layout 113 7.2 TestSerial packet layout 114 7.3 Backing array methods 115 7.4 Sending packets with mig and MoteIF 117 7.5 Interface for handling received packets 117
  • 19. xiv List of code examples 7.6 Receiving packets with mig and MoteIF 117 7.7 Constants and packet layout for Oscillscope application 118 7.8 Class generated by ncg 119 7.9 Simplified code to save received samples 119 7.10 Reliable transmission protocol in Java – transmission 121 7.11 Reliable transmission protocol in Java – transmission 123 7.12 A reliable TestSerial.java 125 8.1 Instantiation within a generic configuration 130 8.2 The fictional component SystemServiceVectorC 131 8.3 QueueC excerpt 131 8.4 A generic constant sensor 132 8.5 Queue interface (repeated) 133 8.6 QueueC implementation 133 8.7 Representing an ADT through an interface in TinyOS 1.x 135 8.8 Timers without parameterized interfaces 135 8.9 Timers with a single interface 136 8.10 HilTimerMilliC signature 137 8.11 ActiveMessageC signature 138 8.12 Signature of TestAMC 138 8.13 Wiring TestAMC to ActiveMessageC 138 8.14 A possible module underneath ActiveMessageC 139 8.15 Parameterized interface syntax 140 8.16 Dispatching on a parameterized interface 140 8.17 How active message implementations decide on whether to signal to Receive or Snoop 140 8.18 Defining a parameter 141 8.19 Wiring full parameterized interface sets 141 8.20 Default events in an active message implementation 142 8.21 nesC attributes 143 9.1 Partial HilTimerMilliC signature 146 9.2 VirtualizeTimerC 148 9.3 Instantiating VirtualizeTimerC 148 9.4 VirtualizeTimerC state allocation 149 9.5 The TimerMilliC generic configuration 151 9.6 TimerMilliP auto-wires HilTimerMilliC to Main.SoftwareInit 151 9.7 The Blink application 151 9.8 The full module-to-module wiring chain in Blink (BlinkC to VirtualizeTimerC) 152 9.9 CC2420SpiC 153 9.10 CC2420SpiP 154 9.11 CC2420SpiC mappings to CC2420SpiP 154 9.12 The strobe implementation 155 9.13 The AMSenderC generic configuration 158 9.14 AMSendQueueEntryP 159
  • 20. List of code examples xv 9.15 AMQueueP 159 9.16 AMSendQueueImplP pseudocode 160 9.17 BlockStorageC 161 9.18 The full code of HilTimerMilliC 163 9.19 VirtualizeTimerC virtualizes a single timer 164 10.1 AMReceiverC 169 10.2 VirtualizeTimerC 172 10.3 Telos ActiveMessageC 181 10.4 The Matchbox facade 184 10.5 The CC2420CsmaC uses a Facade 185 10.6 AlarmToTimerC implementation 190 11.1 The Send interface 192 11.2 The Leds interface 193 11.3 Toggling a state variable 193 11.4 A call sequence that could corrupt a variable 194 11.5 State transition that is not async-safe 194 11.6 Incrementing with an atomic statement 195 11.7 Incrementing with two independent atomic statements 195 11.8 The first step of starting the CC2420 radio 198 11.9 The handler that the first step of starting the CC2420 is complete 198 11.10 The handler that the second step of starting the CC2420 is complete 198 11.11 The handler that the third step of starting the CC2420 radio is complete 199 11.12 State transition so components can send and receive packets 199 11.13 The Resource interface 201 11.14 Msp430Spi0C signature 202 11.15 Msp320Adc12ClientC signature 202 11.16 The ResourceDefaultOwner interface 203 11.17 The ResourceConfigure interface 204 12.1 ActiveMessageC signature 212 12.2 Arbitration in Stm25pSectorC 215 12.3 McuSleepC: platform-specific sleep code 218 13.1 SynchronizerC: time synchronization for SoundLocalizer 225 13.2 The Counter interface 226 13.3 DetectorC: loud sound detection for SoundLocalizer 231 13.4 The Alarm interface 231 13.5 Atm128AdcSingle: low-level single-sample ATmega128 A/D converter interface 232 13.6 The GeneralIO digital I/O pin interface 235 13.7 The I2CPacket interface for bus masters 236
  • 22. Preface This book provides an in-depth introduction to writing nesC code for the TinyOS 2.0 operating system. While it goes into greater depth than the TinyOS tutorials on this subject, there are several topics that are outside its scope, such as the structure and implementation of radio stacks or existing TinyOS libraries. It focuses on how to write nesC code, and explains the concepts and reasons behind many of the nesC and TinyOS design decisions. If you are interested in a brief introduction to TinyOS programming, then you should probably start with the tutorials. If you’re interested in details on particular TinyOS subsystems you should probably consult TEPs (TinyOSEnhancementProposals),whichdetailthecorrespondingdesignconsiderations, interfaces, and components. Both of these can be found in the doc/html directory of a TinyOS distribution. While some of the contents of this book are useful for 1.x versions of TinyOS , they do have several differences from TinyOS 2.0 which can lead to different programming practices. If in doubt, referring to the TEP on the subject is probably the best bet, as TEPs often discuss in detail the differences between 1.x and 2.0. For someone who has experience with C or C++, writing simple nesC programs is fairly straightforward: all you need to do is implement one or two modules and wire them together. The difficulty (and intellectual challenge) comes when building larger applications. The code inside TinyOS modules is fairly analogous to C coding, but configurations – which stitch together components – are not. This book is a first attempt to explain how nesC relates to and differs from other C dialects, stepping through how the differences lead to very different coding styles and approaches. As a starting point, this book assumes that 1. you know C, C++, or Java reasonably well, understand pointers and that 2. you have taken an undergraduate level operating systems class (or equivalent) and know about concurrency, interrupts, and preemption. Of course, this book is as much a description of nesC as it is an argument for a particular way of using the language to achieve software engineering goals. In this respect, it is the product of thousands of hours of work by many people, as they learned and explored the use of the language. In particular, Cory Sharp, Kevin Klues, and Vlado Handziski have always pushed the boundaries of nesC programming in order to better understand which practices lead to the simplest, most efficient, and robust code. In particular, Chapter 10
  • 23. xviii Preface is an edited version of a paper we wrote together, while using structs as a compile-time checking mechanism in interfaces (as Timer does) is an approach invented by Cory. This book is divided into four parts. The first part, Chapters 1–2, gives a high-level overviewofTinyOSandthenesClanguage.Thesecondpart,Chapters3–7goesintonesC and TinyOS at a level sufficient for writing applications. The third part, Chapters 8–13 goes into more advanced TinyOS and nesC programming, as is sometimes needed when writing new low-level systems or high performance applications. The book ends with an appendix summarizing the basic application-level TinyOS APIs.
  • 24. Acknowledgements We’dliketothankseveralpeoplefortheircontributionstothisbook.FirstisMikeHorton, of Crossbow, Inc., who first proposed writing it. Second is Pablo Guerrero, who gave detailed comments and corrections. Third is Joe Polastre of Moteiv, who gave valuable feedbackonhowtobetterintroducegenericcomponents.Fourth,we’dliketothankPhil’s father, who although he doesn’t program, read the entire thing! Fifth, John Regehr, Ben Greenstein and David Culler provided valuable feedback on this expanded edition. Last but not least, we would like to thank the TinyOS community and its developers. Many of the concepts in this book – power locks, tree routing, and interface type checking – are the work and ideas of others, which we merely present. Chapter 10 of this book is based on: Software design patterns for TinyOS, in ACM Transactions on Embedded Computing Systems (TECS), Volume 6, Issue 4 (September 2007), ©ACM, 2007. http://doi.acm.org/10.1145/1274858.1274860
  • 26. Programming hints, condensed Programming Hint 1 Use the “as” keyword liberally. (page 24) Programming Hint 2 Never write recursive functions within a module. In combination with the TinyOS coding conventions, this guarantees that all programs have bounded stack usage. (page 38) Programming Hint 3 Never use malloc and free. Allocate all state in components. If your application requirements necessitate a dynamic memory pool, encapsulate it in a component and try to limit the set of users. (page 38) Programming Hint 4 When possible, avoid passing pointers across interfaces; when this cannot be avoided only one component should be able to modify a pointer’s data at any time. (page 39) Programming Hint 5 Conserve memory by using enums rather than const variables for integer constants, and don’t declare variables with an enum type. (page 42) Programming Hint 6 Never, ever use the “packed” attribute in portable code. (page 43) Programming Hint 7 Use platform-independent types when defining message structures. (page 44) Programming Hint 8 If you have to perform significant computation on a platform-independent type or access it many (hundreds or more) times, temporarily copy it to a native type. (page 44) Programming Hint 9 Interfaces should #include the header files for the types they use. (page 46) Programming Hint 10 Always #define a preprocessor symbol in a header file. Use #include to load the header file in all components and interfaces that use the symbol. (page 47) Programming Hint 11 If a component is a usable abstraction by itself, its name should end with C. If it is intended to be an internal and private part of a larger abstraction, its name should end with P. Never wire to P components from outside your package (directory). (page 58) Programming Hint 12 Auto-wire Init to MainC in the top-level configuration of a software abstraction. (page 60) Programming Hint 13 When using layered abstractions, components should not wire across multiple abstraction layers: they should wire to a single layer. (page 63) Programming Hint 14 Never ignore combine warnings. (page 68)
  • 27. xxii Programming hints, condensed Programming Hint 15 Keep tasks short. (page 74) Programming Hint 16 If an event handler needs to make possibly long-executing command calls, post a task to make the calls. (page 75) Programming Hint 17 Don’t signal events from commands – the command should post a task that signals the event. (page 77) Programming Hint 18 Use a parameterized interface when you need to distinguish callers or when you have a compile-time constant parameter. (page 141) Programming Hint 19 If a component depends on unique, then #define the string to use in a header file, to prevent bugs due to string typos. (page 149) Programming Hint 20 Whenever writing a module, consider making it more general-purpose and generic. In most cases, modules must be wrapped by configurations to be useful, so singleton modules have few advantages. (page 165) Programming Hint 21 Keep code synchronous when you can. Code should be async only if its timing is very important or if it might be used by something whose timing is important. (page 195) Programming Hint 22 Keep atomic statements short, and have as few of them as possible. Be careful about calling out to other components from within an atomic statement. (page 199)
  • 30. 1 Introduction This book is about writing TinyOS systems and applications in the nesC language. This chapter gives a brief overview ofTinyOS and its intended uses.TinyOS is an open-source project which a large number of research universities and companies contribute to. The main TinyOS website, www.tinyos.net, has instructions for downloading and installing the TinyOS programming environment. The website has a great deal of useful information which this book doesn’t cover, such as common hardware platforms and how to install code on a node. 1.1 Networked, embedded sensors TinyOS is designed to run on small, wireless sensors. Networks of these sensors have the potential to revolutionize a wide range of disciplines, fields, and technologies. Recent example uses of these devices include: Golden Gate Bridge safety High-speed accelerometers collect synchonized data on the movement of and oscillations within the structure of San Francisco’s Golden Gate Bridge. This data allows the maintainers of the bridge to easily observe the structural health of the bridge in response to events such as high winds or traffic, as well as quickly assess possible damage after an earthquake [10]. Being wireless avoids the need for installing and maintaining miles of wires. Volcanic monitoringAccelerometers and microphones observe seismic events on the Reventador and Tungurahua volcanoes in Ecuador. Nodes locally compare when they observe events to determine their location, and report aggregate data to a camp several kilometers away using a long-range wireless link. Small, wireless nodes allow geologists and geophysicists to install dense, remote scientific instruments [30], obtaining data that answers other questions about unapproachable environments. Data center provisioning Data centers and enterprise computing systems require huge amounts of energy, to the point at which they are placed in regions that have low power costs. Approximately 50% of the energy in these systems goes into cooling, in part due to highly conservative cooling systems. By installing wireless sensors across machine racks, the data center can automatically sense what areas need cooling and can adjust which computers do work and generate heat [19]. Dynamically adapting
  • 31. 4 Introduction patch of sensors data sink gateway Internet sensor code (nesC/TinyOS) base station code (nesC/TinyOS) gateway code (Java, C, ...) Figure 1.1 A typical sensor network architecture. Patches of ultra-low power sensors, running nesC/TinyOS, communicate to gateway nodes through data sinks. These gateways connect to the larger Internet. these factors can greatly reduce power consumption, making the IT infrastructure more efficient and reducing environmental impact. While these three application domains are only a small slice of where networks of sensors are used, they show the key differences between these networks and most other computing systems. First, these “sensor networks” need to operate unattended for long periods of time. Second, they gather data from and respond to an unpredictable environment. Finally, for reasons of cost, deployment simplicity, and robustness, they are wireless. Together, these three issues – longevity, embedment, and wireless communication – cause sensor networks to use different approaches than traditional, wired, and human-centric or machine-centric systems. The sheer diversity of sensor network applications means that there are many network architectures, but a dominant portion of deployments tend to follow a common one, shown in Figure 1.1 [21, 26, 30] of ultra-low power sensors self-organized to form an ad-hoc routing network to one or more data sink nodes. These sensor sinks are attached to gateways, which are typically a few orders of magnitude more powerful than the sensors: gateways run an embedded form of Linux, Windows, or other multitasking operating system. Gateways have an Internet connection, either through a cell phone network, long-distance wireless, or even just wired Ethernet. Energy concerns dominate sensor hardware and software design. These nodes need to be wireless, small, low-cost, and operate unattended for long periods. While it is often possible to provide large power resources, such as large solar panels, periodic battery replacement, or wall power, to small numbers of gateways, doing so to every one of hundreds of sensors is infeasible. 1.1.1 Anatomy of a sensor node (mote) Since energy consumption determines sensor node lifetime, sensor nodes, commonly referred to as motes, tend to have very limited computational and communication resources. Instead of a full-fledged 32-bit or 64-bit CPU with megabytes or gigabytes of RAM, they have 8-bit or 16-bit microcontrollers with a few kilobytes of RAM. Rather than gigahertz, these microcontrollers run at 1–10 megahertz. Their low-power radios
  • 32. 1.2 TinyOS 5 Antenna Radio Circuitry USB Serial Expansion Connector Sensors Figure 1.2 A Telos sensor produced by Moteiv. The top of the node has the radio, sensors, and circuitry for the USB connector. The bottom, not shown, has the processor and flash storage chip. The antenna is part of the printed circuit board (PCB). can send tens to hundreds of kilobits per second (kbps), rather than 802.11’s tens of megabits. As a result, software needs to be very efficient, both in terms of CPU cycles and in terms of memory use. Figure 1.2 shows a sample node platform, the Telos , which is designed for easy experimentation and low-power operation. It has a TI MSP430 16-bit microcontroller with 10 kB of RAM and 48 kB of flash program memory. Its radio, a TI CC2420 which follows the IEEE 802.15.4 standard, can send up to 250 kbps. In terms of power, the radio dominates the system: on a pair of AA batteries, a Telos can have the radio on for about four days. Lasting longer than four days requires keeping the node in a deep sleep state most of the time, waking only when necessary, and sleeping as soon as possible. Theothermotediscussedinthisbook,themicazfromCrossbowTechnologyissimilar: it has an Atmel ATmega128 8-bit microcontroller with 4 kB of RAM, 128 kB of flash program memory, uses the same CC2420 radio chip, also runs off a pair of AA batteries and has a similar power consumption profile. Networks, once deployed, gather data uninterrupted for weeks, months, or years. As the placement of sensors is very application-specific, it is rare for networks to need to support multiple concurrent applications, or even require more than the occasional reprogramming. Therefore, unlike general-purpose computing systems, which emphasize run-time flexibility and composability, sensor network systems tend to be highly optimized. Often, the sensor suite itself is selected for the specific application:volcanicmonitoringusesaccelerometersandmicrophones,whiledatacenter provisioning uses temperature sensors. 1.2 TinyOS TinyOS is a lightweight operating system specifically designed for low-power wireless sensors. TinyOS differs from most other operating systems in that its design focuses on ultra low-power operation. Rather than a full-fledged processor, TinyOS is designed
  • 33. 6 Introduction for the small, low-power microcontrollers motes have. Furthermore, TinyOS has very aggressive systems and mechanisms for saving power. TinyOS makes building sensor network applications easier. It provides a set of importantservicesandabstractions,suchassensing,communication,storage,andtimers. It defines a concurrent execution model, so developers can build applications out of reusable services and components without having to worry about unforeseen interactions. TinyOS runs on over a dozen generic platforms, most of which easily support adding new sensors. Furthermore, TinyOS’s structure makes it reasonably easy to port to new platforms. TinyOS applications and systems, as well as the OS itself, are written in the nesC language. nesC is a C dialect with features to reduce RAM and code size, enable significant optimizations, and help prevent low-level bugs like race conditions. Chapter 2 goes into the details on how nesC differs significantly from other C-like languages, and most of this book is about how to best use those features to write robust, efficient code. 1.2.1 What TinyOS provides At a high level, TinyOS provides three things to make writing systems and applications easier: • a component model, which defines how you write small, reusable pieces of code and compose them into larger abstractions; • a concurrent execution model, which defines how components interleave their computations as well as how interrupt and non-interrupt code interact; • application programming interfaces (APIs), services, component libraries and an overall component structure that simplify writing new applications and services. The component model is grounded in nesC. It allows you to write pieces of reusable code which explicitly declare their dependencies. For example, a generic user button component that tells you when a button is pressed sits on top of an interrupt handler. The component model allows the button implementation to be independent of which interrupt that is – e.g. so it can be used on many different hardware platforms – without requiring complex callbacks or magic function naming conventions. Chapter 2 and Chapter 3 describe the basic component model. TheconcurrentexecutionmodelenablesTinyOStosupportmanycomponentsneeding to act at the same time while requiring little RAM. First, every I/O call in TinyOS is split-phase: rather than block until completion, a request returns immediately and the caller gets a callback when the I/O completes. Since the stack isn’t tied up waiting for I/O calls to complete, TinyOS only needs one stack, and doesn’t have threads. Instead, Chapter 5 introduces tasks, which are lightweight deferred procedure calls. Any component can post a task, whichTinyOS will run at some later time. Because low-power devices must spend most of their time asleep, they have low CPU utilization and so in practice tasks tend to run very soon after they are posted (within a few milliseconds). Furthermore, because tasks can’t preempt each other, task code doesn’t need to worry about data races. Low-level interrupt code (discussed in the advanced concurrency
  • 34. 1.3 Example application 7 chapter, Chapter 11) can have race conditions, of course: nesC detects possible data races at compile-time and warns you. Finally, TinyOS itself has a set of APIs for common functionality, such as sending packets, reading sensors, and responding to events. Uses of these are sprinkled throughpout the entire book, and presented in more detail in Chapter 6 and Appendix 1. In addition to programming interfaces, TinyOS also provides a component structure and component libraries. For example, Chapter 12 describes TinyOS’s HardwareAbstraction Architecture (HAA), which defines how to build up from low-level hardware (e.g. a radio chip) to a hardware-independent abstraction (e.g. sending packets). Part of this component structure includes resource locks, covered in Chapter 11, which enable automatic low-power operation, as well as the component libraries that simplify writing such locks. TinyOS itself is continually evolving. Within the TinyOS community, “Working Groups” form to tackle engineering and design issues within the OS, improving existing services and adding new ones. This book is therefore really a snapshot of the OS in time. As Chapter 12 discusses and Appendix 1 presents, TinyOS has a set of standard, stable APIs for core abstractions, but this set is always expanding as new hardware and applications emerge. The best way to stay up to date with TinyOS is to check its web page www.tinyos.net and participate in its mailing lists. The website also covers advanced TinyOS and nesC features which are well beyond the scope of this book, including binary components, over-the-air reprogramming services, debugging tools, and a nesC reference manual. 1.3 Example application To better understand the unique challenges faced by sensor networks, we walk through a basic data-collection application. Nodes running this application periodically wake up, sample some sensors, and send the data through an ad hoc collection tree to a data sink (as in Figure 1.1). As the network must last for a year, nodes spend 99% of their time in a deep sleep state. In terms of energy, the radio is by far the most expensive part of the node. Lasting a year requires telling the radio to be in a low power state. Low power radio implementation techniques are beyond the scope of this book, but the practical upshot is that packet transmissions have higher latency. [23] Figure 1.3 shows the four TinyOS APIs the application uses: low power settings for the radio, a timer, sensors, and a data collection routing layer. When TinyOS tells the application that the node has booted, the application code configures the power settings on the radio and starts a periodic timer. Every few minutes, this timer fires and the application code samples its sensors. It puts these sensor values into a packet and calls the routing layer to send the packet to a data sink. In practice, applications tend to be more complex than this simple example. For example, they include additional services such as a management layer which allows an administrator to reconfigure parameters and inspect the state of the network, as well as over-the-air programming so the network
  • 35. 8 Introduction Application Timer Routing Sensors Radio Figure 1.3 Example application architecture. Application code uses a timer to act periodically, sensors to collect data, and a routing layer to deliver data to a sink. can be reprogrammed without needing to collect all of the nodes. However, these four abstractions – power control, timers, sensors, and data collection – encompass the entire datapath of the application. 1.4 Compiling and installing applications You can download the latest TinyOS distribution, the nesC compiler, and other tools at www.tinyos.net. Setting up your programming environment is outside the scope of this book; the TinyOS website has step-by-step tutorials to get you started. One part of TinyOS is an extensive build system for compiling applications. Generally, to compile a program for a sensor platform, one types make <platform>, e.g. make telosb. This compiles a binary. To install that binary on a node, you plug the node into your PC using a USB or serial connection, and type make <platform> install. The tutorials go into compilation and installation options in detail. 1.5 The rest of this book The rest of this book goes into how to program in nesC and write TinyOS applications. It is divided into three parts. The first is a short introduction to the major programming concepts of nesC. The second part addresses basic application programming using standardTinyOSAPIs.Thethirdpartdigsalittledeeper,andlooksintohowthoseTinyOS APIs are implemented. For example, the third part describes how TinyOS abstracts hardware, so you can write a driver for a new sensor. Chapter by chapter, the book is structured as follows: • Chapter 1 is this chapter. • Chapter 2 describes the major way that nesC breaks from C and C-like languages: how programs are built out of components, and how components and interfaces help manage programs’ namespaces. • Chapter 3 presents components and how they interact via interfaces. • Chapter 4 goes into greater detail into configurations, components which connect other components together. • Chapter 5 covers the basic TinyOS execution model and gives guidance on how and when to use tasks.
  • 36. 1.5 The rest of this book 9 • Chapter 6 takes the material from the prior three chapters and brings it together into an example of writing a fully-fledged application that sends an alarm when a node observes a change in its environment. In the process, it covers the major TinyOS APIs (timing, sensing, communication, and storage). • Chapter 7 details the PC-side tools for communicating with nodes connected over the serial port, and covers the TinyOS serial stack and packet formats. • Chapter 8 introduces more advanced component topics, such as parameterized interfaces and attributes. While applications typically don’t use these mechanisms, they are indispensable when writing reusable libraries and systems. • Chapter 9 goes into wiring parameterized interfaces, which form the basis for most reusable systems.After describing the basic mechanisms for managing interface keys, it goes through four examples of increasing complexity. • Chapter 10 presents eight common TinyOS design patterns: commonly useful and powerful ways of organizing components. • Chapter 11 concludes the advanced programming topics by covering concurrency. It describes asynchronous code, the TinyOS task model, and power locks. • Chapter 12 describes the Hardware Abstraction Architecture (HAA), the three-level hierarchy TinyOS uses to raise low-level hardware abstractions to hardware-independent, application-level services. • Chapter 13 goes step-by-step through an advanced application that identifies the location of an event based on when nodes sense it. It uses lower-layer interfaces to implement time synchronization and high-frequency sampling. • Appendix gives a concise overview of major TinyOS application interfaces. Throughout the book, you will find programming hints: general best-use practices that we’ve distilled from the many users of TinyOS and nesC. These are all listed on the sheet at the front of the book. Finally, the complete source code for example applications presented in this book (in Chapters 6, 7 and 13) is available in TinyOS’s contributed code directory, under the name “TinyOS Programming” – see www.tinyos.net for details.
  • 37. 2 Names and program structure Program structure is the most essential and obvious difference between C and nesC. C programs are composed of variables, types, and functions defined in files that are compiled separately and then linked together. nesC programs are built out of components that are connected (“wired”) by explicit program statements; the nesC compiler connects and compiles these components as a single unit.To illustrate and explain these differences in how programs are built, we compare and contrast C and nesC implementations of two very simple “hello world”-like mote applications, Powerup (boot and turn on a LED) and Blink (boot and repeatedly blink a LED). 2.1 Hello World! The closest mote equivalent to the classic “Hello World!” program is the “Powerup” application that simply turns on one of the motes LEDs at boot, then goes to sleep. A C implementation of Powerup is fairly simple: # include " mote .h" int main () { mote_init (); led0_on (); sleep (); } Listing 2.1 Powerup in C The Powerup application is compiled and linked with a “mote” library which provides functions to perform hardware initialization (mote_init), LED control (led0_on) and put the mote in to a low-power sleep mode (sleep). The “mote.h” header file simply provides declarations of these and other basic functions. The usual C main function is called automatically when the mote boots.1 1 The C compiler, library, and linker typically arrange for this by setting the mote’s hardware reset vector to point to a piece of assembly code that sets up a C environment, then calls main.
  • 38. 2.1 Hello World! 11 The nesC implementation of Powerup is split into two parts. The first, the PowerupC module, contains the executable logic of Powerup (what there is of it …): module PowerupC { uses interface Boot ; uses interface Leds ; } implementation { event void Boot . booted () { call Leds . led0On (); } } Listing 2.2 PowerupC module in nesC This code says that PowerupC interacts with the rest of the system via two interfaces, Boot and Leds, and provides an implementation for the booted event of the Boot interface that calls the led0On2 command of the Leds interface. Comparing with the C code, we can see that the booted event implementation takes the place of the main function, and the call to the led0On command the place of the call to the led0_on library function. This code shows two of the major differences between nesC and C: where C programs are composed of functions, nesC programs are built out of components that implement a particular service (in the case of PowerupC, turning a LED on at boot-time). Furthermore, C functions typically interact by calling each other directly, while the interactions between components are specified by interfaces: the interface’s user makes requests (calls commands) on the interface’s provider, the provider makes callbacks (signals events) to the interface’s user. Commands and events themselves are like regular functions (they can contain arbitrary C code); calling a command or signaling an event is just a function call. PowerupC is a user of both Boot and Leds; the booted event is a callback signaled when the system boots, while the led0On is a command requesting that LED 0 be turned on. nesC interfaces are similar to Java interfaces, with the addition of a command or event keyword to distinguish requests from callbacks: interface Boot } { event void } booted (); } interface Leds { command void led0On (); command void led0Off (); 2 LEDs are numbered in TinyOS, as different platforms have different color LEDs.
  • 39. 12 Names and program structure command void led0Toggle (); ... } Listing 2.3 Simple nesC interfaces The second part of Powerup, the PowerupAppC configuration, specifies how PowerupC is connected to TinyOS’s services: configuration PowerupAppC { } implementation { components MainC , LedsC , PowerupC ; MainC . Boot -> PowerupC . Boot ; PowerupC . Leds -> LedsC . Leds ; } Listing 2.4 PowerupAppC configuration in nesC This says that the PowerupAppC application is built out of three components (modules or configurations), MainC (system boot), LedsC (LED control), and PowerupC (our powerup module). PowerupAppC explicitly specifies the connections (or wiring) betweentheinterfacesprovidedandusedbythesecomponents.WhenMainChasfinished booting the system it signals the booted event of its Boot interface, which is connected by the wiring in PowerupAppC to the booted event in PowerupC. This event then calls the led0On command of its Leds interface, which is again connected (wired) by PowerupAppC to the Leds interface provided by LedsC. Thus the call turns on LED 0. The resulting component diagram is shown in Figure 2.1 – this diagram was generated automatically from PowerupAppC by nesdoc, nesC’s documentation generation tool. PowerupAppCillustratesthethirdmajordifferencebetweenCandnesC:wiringmakes the connections expressed by linking the C version of Powerup with its “mote” library explicit. In the C version, Powerup calls a global function named led0_on which is connected to whatever library provides a function with the same name; if two libraries PowerupC MainC LedsC Boot Leds Figure 2.1 Wiring Diagram for Powerup application
  • 40. 2.2 Essential differences: components, interfaces, and wiring 13 .nc .nc .nc app.c binary nesC compiler Native C compiler Figure 2.2 The nesC compilation model. The nesC compiler loads and reads in nesC components, which it compiles to a C file. This C file is passed to a native C compiler, which generates a mote binary. provide such a function then (typically) the first one named on the linker command line “wins.” Using a nesC configuration, the programmer instead explicitly selects which component’s implementation of the function to use. The nesC compiler can take advantage of this explicit wiring to build highly optimized binaries. Current implementations of the nesC compiler (nesc1) take nesC files describing components as input and output a C file. The C file is passed to a native C compiler that can compile to the desired microcontroller or processor. Figure 2.2 shows this process. The nesC compiler carefully constructs the generated C file to maximize the optimization abilities of the C compiler. For example, since it is given a single file, the C compiler can freely optimize across call boundaries, inlining code whenever needed. The nesC compiler also prunes dead code which is never called and variables which are never accessed: since there is no dynamic linking in nesC, it has a complete picture of the application call graph. This speeds the C compilation and reduces program size in terms of both RAM and code. 2.2 Essential differences: components, interfaces, and wiring The three essential differences between C and nesC – components, interfaces, and wiring – all relate to naming and organizing a program’s elements (variables, functions, types, etc). In C, programs are broken into separate files which are connected via a global namespace: a symbol X declared in one file is connected by the linker to a symbol X defined in another file. For instance, if file1.c contains: extern void g( void ); /* declaration of g */ int main () /* definition of main */ { g(); g (); } and file2.c contains: void g( void ) { printf (" hello world !"); }
  • 41. 14 Names and program structure then compiling and linking file1.c and file2.c connects the calls to g() in main to the definition of g in file2.c. The resulting program prints “hello world!” twice. Organizing symbols in a global namespace can be tricky. C programmers use a number oftechniquestosimplifythistask,includingheaderfilesandnamingconventions.Header files group declarations so they can be used in a number of files without having to retype them, e.g. a header file file1.h for file1.c would normally contain: # ifndef FILE1_H # define FILE1_H extern void g( void ); /* declaration of g */ # endif Naming conventions are designed to avoid having two different symbols with the same name. For instance, types are often suffixed with _t guaranteeing that a type and function won’t have the same name. Some libraries use a common prefix for all their symbols, e.g. Gtk and gtk_ for the GTK+ graphical toolkit. Such prefixes remind users that functions are related and avoid accidental name collisions with other libraries, but make programs more verbose. nesC’s components provide a more systematic approach for organizing a program’s elements. A component (module or configuration) groups related functionality (a timer, a sensor, system boot) into a single unit, in a way that is very similar to a class in an object-oriented language. For instance, TinyOS represents its system services as separate components such as LedsC (LED control, seen above), ActiveMessageC (sending and receivingradiomessages),etc.Onlytheservice(component)nameisglobal,theservice’s operations are named in a per-component scope:ActiveMessageC.SplitControl starts and stops the radio, ActiveMessageC.AMSend sends a radio message, etc. Interfaces bring further structure to components: components are normally specified in terms of the set of interfaces (Leds, Boot, SplitControl,AMSend) that they provide and use, rather than directly in terms of the actual operations. Interfaces simplify and clarify code because, in practice, interactions between components follow standard patterns: many components want to control LEDs or send radio messages, many services need to be started or stopped, etc. Encouraging programmers to express their components in terms of common interfaces also promotes code reuse: expressing your new network protocol in terms of the AMSend message transmission interface means it can be used with existing applications, using AMSend in your application means that it can be used with any existing or future network protocol. Rather than connect declarations to definitions with the same name, nesC programs use wiring to specify how components interact: PowerupAppC wired PowerupC’s Leds interface to that provided by the LedsC component, but a two-line change could switch that wiring to the NoLedsC component (which just does nothing): components PowerupC , NoLedsC ; PowerupC . LedsC -> NoLedsC . Leds ; without affecting any other parts of the program that wish to use LedsC. In C, one could replace the “mote” library used by Powerup by a version where the LED functions did nothing, but that change would affect all LED users, not just Powerup.
  • 42. 2.3 Wiring and callbacks 15 2.3 Wiring and callbacks Leaving the component connection decisions to the programmer does more than just simplify switching between multiple service implementations. It also provides an efficient mechanism for supporting callbacks, as we show through the example of timers. TinyOS provides a variable number of periodic or deadline timers; associated with each timer is a callback to a function that is executed each time the timer fires. We first look at how such timers would be expressed in C, by modifying Powerup to blink LED 0 at 2 Hz rather than turn it on once and for all: # include " mote .h" timer_t mytimer ; void blink_timer_fired ( void ) { leds0_toggle (); } int main () { mote_init (); timer_start_periodic (& mytimer , 250 , blink_timer_fired ); sleep (); } Listing 2.5 Powerup with blinking LED in C In this example, the Blink application declares a global mytimer variable to hold timer state, and calls timer_start_periodic to set up a periodic 250 ms timer. Every time the timer fires, the timer implementation performs a callback to the blink_timer_fired function specified when the timer was set up. This function simply calls a library function that toggles LED 0 on or off. The nesC version of Blink is similar to the C version, but uses interfaces and wiring to specify the connection between the timer and the application: module BlinkC { uses interface Boot ; uses interface Timer ; uses interface Leds ; } implementation { event void Boot . booted () { call Timer . startPeriodic (250); } event void Timer . fired () {
  • 43. 16 Names and program structure call Leds . led0Toggle (); } } Listing 2.6 Powerup with blinking LED in nesC (slightly simplified) The BlinkC module starts the periodic 250 ms timer when it boots. The connection between the startPeriodic command that starts the timer and the fired event which blinks the LED is implicitly specified by having the command and event in the same interface: interface Timer { command void startPeriodic ( uint32_t interval ); event void fired (); ... } Finally, this Timer must be connected to a component that provides an actual timer. BlinkAppC wires BlinkC.Timer to a newly allocated timer MyTimer: configuration BlinkAppC { } implementation { components MainC , LedsC , new TimerC () as MyTimer , BlinkC ; BlinkC . Boot -> MainC . Boot ; BlinkC . Leds -> LedsC . Leds ; BlinkC . Timer -> MyTimer . Timer ; } Listing 2.7 Powerup with blinking LED configuration (slightly simplified) In the C version the callback from the timer to the application is a run-time argument to the timer_start_periodic function. The timer implementation stores this function pointer in the mytimer variable that holds the timer’s state, and performs an indirect function call each time the timer fires. Conversely, in the nesC version, the connection between the timer and the Blink application is specified at compile-time in BlinkAppC. This avoids the need to store a function pointer (saving precious RAM), and allows the nesC compiler to perform optimizations (in particular, inlining) across callbacks. 2.4 Summary Table 2.1 summarizes the difference in how programs are structured in C, C++ and nesC. In C, the typical high-level programming unit is the file, with an associated header file that specified and documents the file’s behavior. The linker builds applications out of files by matching global names; where this is not sufficient to express program structure (e.g. for callbacks), the programmer can use function pointers to delay the decision of which function is called at what point.
  • 44. Another Random Document on Scribd Without Any Related Topics
  • 45. by the mate, who prevented the explosion that was about to take place by informing him that the men had refused duty. "Refused duty!" said the captain; "what can that mean?" "Why, sir, they say they won't go to sea unless you ship a man in the place of the one that died." "But I can't now," said he; "the ship must go right to sea, and no one would go on such a short notice." "I've told them that, sir, but that villain, Brock, has made the rest ugly." Capt. Nelson returned on shore and spent half an hour in a vain attempt to find a sailor who would go immediately to sea. Returning on board he asked me to go into the forecastle and try to persuade the men to turn to. I did what I could, but of course a boy's talk was not much heeded, and I got rather scared myself by their curses and threats. Then the mate came to the door and asked in a shaky voice, "Are you going to turn to?" "When that man comes aboard," was Brock's defiant answer. Mr. Smith hastened back to report that they still refused duty, and the captain hailed a passing boat and procured some Russians from the "Captain of the 'Branvault,'" as the harbor-master is called. With their assistance the ship was hauled to the Mole-head, and gave her hawser to the towboat that was waiting outside. Then the Russians stepped ashore, I took the wheel, the mates cast off the lines, and we proceeded in tow of the steamer. When fairly off, the captain told the mate to call all hands aft. Standing by the cabin door he made an address to them, offering to divide among them the wages that would have come to the dead sailor, had he lived to complete the voyage. Some of the men were inclined to give in, but Brock muttered, "We don't want a dead man's wages."
  • 46. "Well," said the captain, "I'll give you what I should have paid another man if I had shipped one." "Oh, we've been humbugged that way before, Cap'n," said Brock, who turned and went forward, followed by the rest of the crew, leaving the captain in the midst of another conciliatory harangue. The ship was soon abreast of Tollbaken, ten miles from Cronstadt. The wind was dead ahead; and having nominally sailed, the captain decided to come to anchor and wait for the wind and crew to favor him. The mate asked the men if they would turn to and let go the anchor; and thinking they would thus gain their point, and also their dinner, they consented. The steamer was cast off and the ship brought to anchor. The crew were then allowed to get their dinner, but when called on to work, they again refused. The captain was greatly troubled, and so much at a loss what to do, that he appealed to me for advice. I felt rather flattered by his consideration, and suggested that he should put the men in irons. He was afraid to try that, so I proposed that he should give them nothing to eat till they resumed duty. When supper-time came they went to the galley, and being refused, Brock marched aft with his tin pot in hand, and with the coolest impudence, asked the captain if they were not to be allowed any supper. "Not till you turn to," was the reply. The man then put on an air of injured innocence and declared it was a shame to try to starve men to death. But he sauntered forward, and the men turned in, laughing at the way they had "waxed the old man," but feeling a little concerned on the score of eating. At nine o'clock in the evening, the wind hauled fair. The captain went to the forecastle, and after fifteen minutes spent in argument upon the propriety of their going to work, the promise of some tea, and other fair words, prevailed upon the men to get the ship under way, and the passage was fairly begun.
  • 47. We passed through the Baltic and by Elsinore without any remarkable occurrence, except the increased independence and insolence of the crew. They felt that the Cronstadt disturbance had proved there was no fight in the officers, and some of the crew showed more zeal in taking their comfort than in obeying orders. Brock particularly distinguished himself. He boasted in the forecastle that he was going to try to induce an officer to strike him, in order that he might raise some money by a lawsuit on arriving in New York. One day the ship was running before a strong breeze, under the main-top-gallant-sail. Brock was at the wheel, and, being a miserable helmsman, was letting the ship yaw about two points each side of her course. "Keep her straight," said the captain. "I should like to see any one keep her any straighter," was Brock's answer; and upon this the captain took hold of the wheel to prove that it could be done. Instead of stopping to witness the proof, Brock started forward. "Come back here!" shouted the captain. "One's enough to steer the ship," was the polite answer, and the fellow made for the forecastle, leaving the captain working the wheel, unable to leave it until relieved. The mate, finding out the trouble, went to the forecastle and saw Brock leisurely lighting his pipe. "Go aft and take the wheel again! What business have you got here?" "Don't you fret; I'll come out when I get ready," said Brock. The mate turned away and sent another sailor to relieve the captain. After Brock had finished his smoke, he appeared again on deck, and politely asked Mr. Smith if he had a job for him. The mate gave him a few of his opinions about his behavior, and set him at work aloft. That night, in the first watch, I was keeping the mate company on deck, and hearing Mr. Smith's complaints about Brock. "Why don't
  • 48. you knock him down?" said I. "That's the only kind of treatment such a man can understand." "I'll tell you why I don't," said the mate. "About five years ago I was mate of the ship "Neptune" in the Liverpool trade. We hove up our anchor in the River Mersey and were being towed out to sea. I was anxious to get the anchor catted as soon as possible, as the pilot wanted sail made on the ship, and I had all the crew on the forecastle, heaving on the capstan. An ugly-looking Liverpool Irishman, called Jim Kelley, was holding the turn, and just as the anchor was about up to the cat-head he let go the rope; it flew around the capstan at a lively rate, and the anchor went down. "I growled at him for it, and he said it slipped away from him. We went at it again, and had the anchor half-way up, when Kelley surged the fall and let it go again. It was raining at the time, and things were very slippery, and he pleaded that as his excuse; but I thought I saw mischief in his eye. The end of the fall had hit two of the men pretty severe blows, as it flew around the capstan. I was pretty mad by this time, and told him if he did that again I'd knock his head off. I thought he'd hold on the next time, but just as I was going to say, "Heave a pawl!" down went the anchor for the third time. I heard the pilot rattling off a string of oaths as long as the maintop-bow-line, and I stepped up to Kelley and gave him a touch of my fist that sent him head first off the top-gallant forecastle on to a pile of chain cable. He didn't feel like holding any more turns for a day or two, you may bet, and the rest of the crew said it served him right. But when we got into New York I was hauled up in court for it, and had to pay fifty dollars fine. Now I've got a wife and five children, and as good-looking ones as you'd wish to see they are, too, though I say it, and my wages are all they have to support them. That villain Brock, is a good deal of a sea-lawyer, and if I lay my hand on him, it's only taking the bread out of my little ones' mouths and giving him rum money. I made a vow after that time that I'd never strike a man again."
  • 49. "But what can you do," said I; "you ought to keep good discipline. Hasn't the captain got any legal power to punish ugly sailors?" "Yes," said Mr. Smith, "the captain has power, but he doesn't want to be troubled, and it's considered the mate's place to keep the men straight. Once I went to a captain and reported an impudent sailor, and the only satisfaction I got was, "What did you come here for if you can't take care of the crew," and I got turned out of the ship at the end of the voyage. I made a vow then that I'd never complain to the old man again; so between my two vows I don't see that I've got much chance with a sailor that's bent on making a row. If this ai'n't a dog's life, I'd like to know what it is." All the way across the Atlantic the sailors may be said to have had charge of the ship, and did about as they pleased. Brock's insolence was beyond all bounds, and it seemed incredible that it should be submitted to by the captain and officers. He was evidently in a desperate mood to get struck, and one evening at eight o clock, when the captain kept his watch up a few minutes to take in the top-gallantsails, as a stormy night was coming on, Brock stepped up to him and said, "Cap'n, it's too late for you to try and humbug us now. It's our watch below." The captain sputtered some bad words at him, and told him he was no sailor: but the hoped-for blow was not given. The passage ended at last, and New York was reached, none too soon for all on board. The day after arrival, the crew came to the ship to be paid off, and Brock called the mate aside and made this startling speech: "Mr. Smith, I want to beg your pardon for the way I behaved on this voyage. You're the kindest man ever I sailed with, and I know I ought to be ashamed of myself. I can show you the marks on my head where the last mate I was with split it open with a belaying pin, and I deserved it too. You'd have done right if you had served me the same way. What would my good old mother have said if she had known what a wretch I have been! She used to pray with me, and beg me to be a good man. Now that she's dead, her words sometimes haunt me, and I have made up my mind that I'll
  • 50. be a different man for the rest of my life." A tear stood in his eye, and good Mr. Smith took his hand and said, "I don't bear you no ill- will, Brock. I don't harbor malice towards nobody living. If a man should cut my throat, I believe I'd forgive him the next minute." As he turned away, he caught a whiff of Brock's breath, and the suspicion came sadly to his mind that this repentance was not so much the result of piety as of whiskey. This story reminds me of a little incident that occurred in Bombay when I was mate of the "Lizzie Oakford." There were two English ships anchored, one on each side of us. It was a calm morning, and we could hear some of the words spoken on board these vessels. A little after breakfast our attention was attracted to the ship on the port side, by the sound of angry voices. The captain was having an altercation with some of his crew, and very soon passed from words to blows. He "ended" four or five of them over, and with every stroke of his fist we could hear him swear about the Act of Parliament. In the course of half an hour we heard a row on board the ship on the starboard side, and looking towards her we saw a number of her crew on the poop-deck. One of the sailors had seized hold of the mate's coat-tail, and was whirling him around in a circle, while another, with a folded strip of canvas, belabored his back every time he flew past. Our second mate was so indignant at this insult to his cloth that he wanted to board the vessel and fight the sailors on his own account, but he said he should want to "lick the mate too." "There," said he, "are the two extremes, and we are the middle. In one ship the officers abuse the sailors, and in the other the sailors abuse the officers. Here there hasn't been much of either yet awhile, though I think the old shell-backs have got a little the best of it." We ran down the trades, and keeping well to the southward in order to catch the "brave westerlies" as soon as possible, we came in sight of Tristan d'Acunha, a noble, symmetrical mountain island, 8,326 feet high, its top covered with snow. We were becalmed in sight of it for several hours, and enjoyed resting our eyes, wearied with gazing for weeks upon the dancing water, by fixing them on this grand, immovable mass. Books gave an interesting account of a colony
  • 51. formed here; but we were not near enough to perceive any signs of human life. The lazy rolling of the bark in the swell, made even the idea of a residence on the snowy peak seem attractive, and there was comfort in thinking of a future world which is to be all land. A breeze, springing up from the north-east, gradually freshened. The sea being quite smoothed down by the calm, we were able to carry a press of canvas; and with all sail set and the yards braced up, the bark lay down on her side, and made a run of 261 miles in 24 hours, and the day after, she made 252 miles. The fore topgallantmast was then found to be sprung, and a new one had to be put in its place. While sending it up, we overtook and passed a brig, loafing along under reefed topsails, evidently seeming to think it was blowing a gale of wind, whereas we had our main-royal set. This showed why some vessels make long passages. We sped along swiftly, passing the Cape of Good Hope when 61 days out, and running along the parallel of 40° S., a succession of gales helped us onward. The weather was chilly, often wet and disagreeable, but our good progress kept us cheerful. One night was especially exhilarating, when running in a north-west gale, with the wind quartering, under reefed canvas, the bark flying away, at the rate of 14 knots, from wind, rain, thunder, lightning and towering waves. There is some sublimity in a sailor's life, and this wild scene was a good specimen of it. I enjoyed standing by the bitts and singing at the top of my voice some hymns expressing trust in the Creator, knowing that the noise of the elements made the sound inaudible to the crew. As we neared Amsterdam Island, the weather continued rainy, and there was no chance for observations by which to verify our position. On the day I expected to pass it, the sun appeared, most providentially, just at noon for a moment. I caught the altitude with my sextant and found the latitude. But I had no means of determining the longitude. We were a few miles south of the latitude of the island, so I steered due east, keeping a hand on the lookout to watch for the land, as I desired to sight it to verify the reckoning and the chronometers. No land appeared; a dark night was coming on, and I felt anxious at running down so nearly in the
  • 52. latitude of the island; but at evening-time it was light, and at 6, p.m., we saw the noble mass of land, nearly three thousand feet high, bearing off the weather-quarter. We had already sailed by it, within five miles distance. One feature of great interest in these latitudes is the presence of sea-birds. The noble Albatross, the king of sea-birds, is almost always in sight, floating in the air about the vessel, no matter how fast she goes. Its wings seldom move, and what its propelling power is, no one can tell. It seems to depend only on its volition. The Stormy Petrel or "Mother Carey's Chicken," is here and everywhere else on the ocean. The pretty white and black Cape Pigeons flock in the wake. We caught several of these with small fish-hooks, and tried their value as component parts of a pigeon-pie, but the flavor was rather strong and oily. The homely, black Cape Hens are numerous also. They always bring to my mind a scene witnessed on a former voyage. Coming on deck one Sunday, I found the mate and passengers engaged in tying pieces of pork and bits of red flannel at each end of a string and throwing them overboard. The Cape Hens greedily swallowed the pork, and several of them were flying about with streamers hanging from their mouths; another trick was to tie several pieces of pork to the same string. Two or three birds darting at these, and each swallowing a piece, they would rise in the air tied together. I took the part of the hens on this occasion, and let the mate brace the yards for a while. The weather was cool in these latitudes, and it was no longer agreeable to sit on deck. Our evenings were usually passed in the cabin, and I employed some of the hours in reading to the passenger an account of my experiences in the ship Dublin. I explained to him that it was written while I was officer of a ship, and had no leisure to attempt literary embellishment. Its sole object was to record the events relating to the management of the crew, and I requested him to forbear criticism of its style.
  • 53. CHAPTER III. THE VOYAGE OF THE "DUBLIN." MY first voyage, as officer, was made in the good ship "Dublin." She was six hundred tons register, and of the style said to be built, Down East, by the mile and sawed off. Her bow and stern were so square, they gave an impression of truth to this statement, but for all that she was a staunch, well built vessel, and though twenty-one years old was still an able and trustworthy ship. Her worthy owner, one of the merchant princes of Boston, used to go down on the wharf and rub his hands with delight when the old "Dublin" came into port. She was his favorite ship, and her blunt bow was more attractive to him than the rakish model of the modern clippers. He would tell how the copper bolts were driven into her, only one inch a day, to make them "fit solid;" how the timbers were "scarfed" and "dowelled," and many other things that it would need a ship builder's manual to interpret. He considered a great honor had been done me, by the permission to go to sea as third mate of her, and shook his head with misgivings when he heard that the captain had engaged so young and inexperienced an officer. I had been to sea four voyages, one of them over fourteen months around the world, before the mast. I could hand, reef and steer, and do the ordinary work on the rigging, as well as most sailors, so I did not consider my presumption very great. Captain Streeter, her commander, was a fine-looking man of about forty years. He was tall and well formed, with dark complexion, black hair, beard and moustache, and a coal-black, flashing eye that bespoke a strong will and a passionate nature. He was very fluent in speech, and gave the impression on a first hearing that he was what sailors call "a blower."
  • 54. When he engaged me, he gave a long and impressive harangue. He didn't want an officer that was afraid of sailors, but at the same time he allowed no one to abuse the crew, and especially objected to the use of profane language, which he condemned as the most foolish of practices. He appointed the day for me to come on board and I left him pleased with my success, but with a lurking suspicion that my fair-talking captain might prove to belong to the class known as "shore-saints and sea-devils." The owner, however, was one of the best men living, a noble philanthropist, and a vice-president of the Seamen's Friend Society. I therefore felt some assurance that his ship would have a respectable captain and be well conducted. At six o'clock, one dark morning in the end of November, my fond father bade me farewell at the door, as I left my pleasant home and its gentle occupants, and trudged to East Boston, in a storm of sleet, to enter upon a sphere and mingle with associates so contrasted, that I needed no other illustration, for the next few months, to impress upon my mind the two extremes of the future life. The ship was bound to Richmond, Virginia, in ballast, there to load a cargo of tobacco for the Mediterranean. In the forenoon, a negro crew of fourteen men and two boys came on board. They were mostly fine "strapping" fellows, with bright eyes and shining "ivories," and as we proceeded down the bay they made the decks ring with their songs; the main-topsail going to the mast-head to the tune of "Come down you bunch o' roses, come down," and the fore- topsail halyards answering to the strong pulls following the sentiment: "Sally Brown's a bright Mulatto, She drinks rum and chews tobacco." A man who was loosing the mizzen-top-gallant-sail was heard to utter some profane exclamations over the bunt gasket, which was made fast with a knot that resisted all his efforts at untying, being what sailors call "an anti-gallican hitch." As I have mentioned, Capt. Streeter had remarked a few days before that he allowed no profane language on board of his ship, and I wondered if he would take any
  • 55. notice of this; but I did not wait long before having my curiosity satisfied. The same thought probably came to the captain's mind, for he stepped to where he could get a good look at the man, and then began: "Button your lip up, or I'll knock spots out of you. I don't allow swearing on board of this boat;" with more to the same effect, accompanied by several profane epithets. It was evident that the captain's fluency of speech was not limited to polite conversation, and his consistency was explained by his remarking, at a future time, that his rule on board ship was, "do as I order, not as I do." The Pilot left at Boston Light. All hands were busily employed putting things to rights, for a ship is seldom in order except when at sea. There, men are constantly laboring to keep everything "ship-shape" and tidy, and the moment the vessel is moored at the wharf, crew and officers generally go over the side, stevedores, riggers and carpenters take possession, and the decks are in a turmoil until she is again out of the range of visitors. It surprised me to see the captain interesting himself in all the work, for in previous voyages its execution had been left entirely to the officers. While the mate was securing the anchors, the captain visited the top-gallant forecastle and offered suggestions, which the high-spirited first officer treated with a contemptuous silence. The black eyes shone with suppressed rage, and their owner transferred his interference to the second mate's labors, which were being employed in putting on chafing-gear. He soon worked this officer into such a flurry, that he hardly knew whether he stood on his head or his heels, and then after putting a stop to a job the carpenter had undertaken, and peeping into the cook's boilers to see how much beef they contained, to the delight of all, he disappeared into the cabin, but in a few minutes his loud tones showed that the steward was the object of his attentions. In the evening, after the watches were chosen, the captain joined the officers on deck and talked familiarly with us, illustrating his remarks by anecdotes and comparisons more amusing than refined. We were obliged to confess to each other that he was a very
  • 56. agreeable man in private, and for a time forgot all the mental imprecations we had bestowed on him during the day, on account of his interference with the work. The mate and second mate had a talk by themselves concerning their duties, and the second mate, while expatiating upon his own good qualifications, put his hand in his pocket and pulling out a pair of brass knuckles put them upon his hand. Holding his fist up, he said: "I always carry my tools with me, and if you ever want any work done, you have only to say the word, and you'll find me on hand like Day and Martin's blacking." "I don't want you to let me see those things again, while you're on board of this ship," said the mate. "Why so; do you intend to let those sailors play Isaac and Josh with you?" "No," said the mate, "but when I can't keep men in order, without using such weapons as that, I'll give up to some one who can. I never knew a man yet who carried such things but he proved to be a coward at heart." "No man can call me a coward," replied the second mate in an angry tone. "Well," said the mate, "I hope you are not one, but I shall think better of you if I hear nothing more about brass knuckles." This was not a very pleasant opening of acquaintance, and both parties took at the outset a dislike to each other. I gained from each of them a brief account of their antecedents. Mr. Morrison, the first mate, was a Scotchman by birth, about forty- two years of age. He had been captain of English vessels, but having met with misfortunes, concerning which he was very reticent, he had begun to seek his fortune in the American merchant service. He was a short, thick-set man, with a ruddy complexion and a cast of countenance expressing courage and determination. His bearing was
  • 57. significant of "Scotch pride." He was a man of much intelligence and had received a good education. Mr. Howard, the second mate, hailed from the State of Maine. He was of medium height and well built, but had a brutal look and seemed ordinary in intelligence. He frankly confided to me the immediate occasion of his shipping in the "Dublin." "Last voyage I was second mate of the 'Minerva.' We had a nigger crew and used 'em pretty rough I must say; but I had 'em in such good discipline that one day I got mad with a 'moke' about something and I told him to lay his head down on the hatch for I was going to chop it off. He did just as I told him, and though he thought I was going to kill him, he didn't dare to move or say his soul was his own. That's what I call good discipline. "We kept them under well enough at sea, but when we got into Rio Janeiro, what did the scamps do but set fire to the ship, and burn her up; and two days after a gang of 'em caught me one evening in the street, and gave me such a pounding that I couldn't see out of my eyes for a fortnight. I believe they'd have killed me if the police hadn't come along and rescued me. I vowed then I would sail just once more with a nigger crew, and from what I hear of this captain, I think he's just the man that'll suit me." The "Dublin" had a fair start. In three days we sighted the Capes of Virginia and in two more worked up the James River to City Point. City Point then consisted of about twenty dwelling houses beside the negroes' cabins, and had wharves at which the vessels lay while receiving their cargoes of tobacco, which came to them in lighters from the city of Richmond, about thirty miles above, the shallowness of the river preventing anything but vessels of light draft from proceeding there. The tobacco was packed in large hogsheads, weighing from one thousand to eighteen hundred pounds, and as the crew hoisted them in they kept up a song from morning till night. Negro stevedores from the shore stowed them in the hold, and the captain spent almost all his time down there, watching that they saved all the room possible, frequently making them "break
  • 58. out" again, to the great disgust of the negroes. I heard one of them saying to the others: "I nebber see such a man as dis cap'n afore; he tinks he knows eberyting and nobody else don't know nuffin." There was of course nothing here to interest us beyond receiving our tobacco, and when the ship was loaded to sixteen feet draft she dropped down the river ten miles, into deeper water, and there completed her cargo. On a fine clear day in the end of December, we left the shore of Virginia astern and steered for the Straits of Gibraltar. Fresh and favorable winds prevailed for several days and we made good progress on our voyage. One evening the captain in a confidential mood read us some extracts from the owner's letter of instructions, and was particularly merry over the latter part of it, which read: "You will distribute to the men the books and tracts which are supplied. You will endeavor to suppress all vice and immorality on board of your vessel and use your best efforts to promote the welfare of your crew." The inmates of the ship now felt acquainted with each other, and as a general thing their good opinions were very much modified. Capt. Streeter having no taste for reading, and being a man of energetic and active temperament, could not content himself in his cabin, and was almost constantly on deck roaming about the ship, criticizing every job of work, "in every body's mess and nobody's watch." When bracing yards, making or taking in sail, he would stand on top of the house, and accompany his orders with volleys of oaths, provided things were not done exactly to his mind. If the crew did not move quite actively enough, and nothing in this way would suit him but the "clean jump," every blackguard epithet that his fluent tongue and inventive brain could command was heaped upon them: Scoundrels, black scorpions, and names too filthy for utterance were their common titles at such times, and when the men and officers did so well that he could not find a point to censure, he seemed
  • 59. rather disappointed at losing an opportunity for this favorite employment. Sailors call such a man, "a blower." At night no one was allowed to sit down on deck, and though no work was to be done, the sailors had to keep on their legs. Such strict rules of course gave the officers a good deal of disagreeable work. From eight to twelve at night the men would have to walk the deck, unless engaged in working ship, and when at four o'clock, a.m., they were roused out, after four hours slumber, they could not always resist the temptation to sit down on a spar, or lean over a water-cask. In spite of their efforts to keep awake, their heads would drop upon their arms and they would fall asleep. If anyone wishes to experience something which in his recollections will serve as a synonym for misery, let him sail in such a ship and stand the morning watch. In the hour from four to five as he stumbles about the deck, endeavoring to drive away the drowsiness that weighs down his eyelids, he will feel a wretchedness, which, unless he is a very unfortunate man, will seldom, if ever, be surpassed during his life. The mate failed to carry out these orders very strictly, as he knew it could only be done by harsh measures; for though his fiery temper often led him to strike a blow at some unlucky sailor, he despised all premeditated schemes to abuse or oppress them. Besides this, he thought he saw through the captain's character. He imagined that he was anxious to gain for the "Dublin" the reputation of being a "hard" ship, provided his officers would do all the necessary "dirty work," but was unwilling to expose himself to the present dangers of fighting, or the future disgrace of lawsuits. Their relations to each other were not very pleasant, for the mate was jealous of the captain's interference with his work, and the captain, perceiving his state of mind, attempted to retaliate by little acts of oppression, of which one will be sufficient to show the spirit. The mate's room was very small. His only convenience for writing up his log book was at a narrow standing desk, where he was too much cramped to do it neatly.
  • 60. At the beginning of the passage he sat down at the table in the forward cabin to perform this part of his duty, and the captain coming from his spacious after-cabin found him there at work. Upon seeing him he drew himself up, and in a pompous way said: "Mr. Morrison, I want you to understand that my cabin table isn't a writing desk for officers." "Oh, indeed," said the mate. "I've always been accustomed to have the use of it even for my private writing, and I had no idea you would object to my writing the ship's log here." "You must learn you ai'n't aboard one of your lime-juice ships now," was the courteous response, and the mate retired to his room, his Scotch pride and temper almost overcoming his desire to respect the captain. But the second mate was a man after the captain's own heart. It was only necessary to show him the way to the captain's good graces, and his subservience joined to his own brutal passions made him an earnest disciple. The crew were a pretty independent and saucy set of negroes, and required a strict hand to keep them under. From the very first there had been almost daily little difficulties, and at one time at City Point a general knock-down was only prevented by the mate's interfering between the second mate and a sailor, to the great wrath of the former. A few days after leaving the Chesapeake, Mr. Howard was going around the deck at about half-past four in the morning, and found a man called Brooks sitting down and nodding. He awakened him very suddenly by raising him up by the ears, and then set the whole watch to work bracing the yards "in" a little. The men were sleepy, and cross at this "humbugging," for they knew the wind had not altered at all, and this was merely a "work up job." They were not very prompt with their Aye, aye, sir. "Haul in the top-gallant-brace" said the officer. No answer followed, but he saw the order was obeyed.
  • 61. "Belay!" Still no answer. "Sing out," said he; "if you don't open your gills I'll slaughter you. Haul in the royal-brace!" No answer. He turned in a rage and catching hold of Brooks, who was nearest him, gave him a blow with his brass knuckles that would have unsettled any ordinary head. But the darkey's skull was not very sensitive, and he at once drew his sheath-knife, and stabbed Howard in the abdomen. He had on thick clothes, and the knife after cutting through them inflicted only a small flesh wound. Howard was rather frightened by this episode, and not knowing how badly he was cut, upon seeing the other men seize handspikes and belaying pins ready to join Brooks, in case of any further attack, he thought it best to retreat. After breakfast he reported the case to the captain, who sent for Brooks to come into the cabin, where he took his position with a pistol and a fathom of ratline stuff. Having shut the door, so that there should be no witnesses, he made the man take off his shirt; and then flogged him till the blood flowed down his back, and the man's cries and promises made him desist. The captain's prompt espousal of the second mate's cause showed that he would stand by his officers, and it had the effect of making the crew more respectful and careful. Being the third mate, I was of course in the mate's watch; my duty was to follow up the execution of the mate's orders, and look after the little details of work. I must know the place for everything and see that it was in its place. When the decks were cleared up at night, if the mate in his inspection spied a stray marline-spike or serving-board, it was the third mate who had to answer for it. If a sailor wanted spunyarn or seizing-stuff to work with, it was the third mate who must know where to find it and run and get it, or if the lockers were not in order or the tar-barrel fetched adrift he was the first looked at for blame. In his turn of course he could growl at the
  • 62. sailors, but that was rather poor satisfaction, and he had not filled his office many days before he came to the conclusion that it was a most thankless billet, and that a third mate's portion contained "a larger share of kicks than of coppers." I was only nineteen years old. The sailors looked upon me as a youngster, and were not inclined to be particularly respectful, thinking I wouldn't dare to use force with them. The captain watched me very closely, wishing to train me up in the way I should go, and many a harsh-sounding order or rebuke I got from him on deck, all the more galling because given in the presence of the men. But personally the captain seemed favorably inclined toward me, or else he feared lest I might make a report of his doings to the owner, and thus sought frequent opportunities to talk with me and smooth over my ruffled feelings. It is not customary for a captain to have any conversation with a third mate, and I was not quite sure as to his motive, though I leaned to the latter opinion, judging from the tenor of all his stories, talk and advice, which was to the sole end of discipline, or, perhaps more exactly, of fighting sailors. In consulting with the mate as to this he gave me a decided opinion. "All the old man wants," said he, "is to have you tarred with the same brush as himself, and then he thinks you wouldn't injure him ashore, for you know it doesn't do for the pot to call the kettle black." One day we were reefing the mizzen-topsail and I was astride of the yard-arm hauling out the weather earing. The captain saw from the deck that the men had not gathered up all the slack sail on top of the yard, before tying the reef-points; and he at once set up a roar of mingled oaths and orders, which, with a storm howling past my ears produced a bewildering effect. With some difficulty I divined the pith of his remarks, and gave the necessary directions; but this was not enough for the captain, who sang out to me, "What's the use of sitting there and talking to them, get up on the yard and kick their heads off." A good deal more followed, but I was too angry to hear anything else and paid no attention.
  • 63. The captain saw that I was rather out of sorts for the rest of the day, and in the dog-watch came up to me as I was leaning against the booby-hatch and began in his pleasant fluent way to tell me a story. "You never met Mr. Jones of Baltimore did you?" "No sir, I never did." "Well, he was my second mate, when I had the ship 'Daphne' in the China trade." I had heard from good authority on shore that the "Dublin" was the only ship Capt. Streeter had ever commanded, and since being at sea with him I had learned that Mr. Jones was his ideal officer, and whenever he wished to give a hint to his present mates upon points where he felt he could not command, his favorite and usual method was to convey it in a story about Mr. Jones, and Mr. Jones' name had already become a by-word among the officers. I knew what was coming and prepared to receive instructions. "Mr. Jones," continued the captain, "never went aloft to reef topsails without having a belaying pin stuck into the leg of his boot. He used to take his stand in the slings of the yard, and if the sail wasn't picked up pretty lively, before you could count twenty he would have been out on both yard-arms, and hit every man a tap on the head that made 'em take hold like young tigers. Then when the sail was reefed he'd sing out, 'lay down,' and as every man got into the rigging, if he wasn't mighty spry, he'd get helped along with a kick, and then he followed the last man down and jumped on his head and shoulders, if he could overtake him. I tell you it was fun to see them scatter when he said 'lay down.' They would come sliding down the backstays like a parcel of monkeys, and once a Dutchman, who happened to be the last man, and saw the second mate's boots just above his head, got so frightened that he jumped down from half way up the main-rigging and broke his leg. I had to scold Jones though a little for that, as the galoot was laid up the rest of the voyage."
  • 64. "I should think that was rather poor economy," said I, "to lose a man's labor for several months, for the sake of gaining a few seconds time in getting down from aloft." "It paid though, after all," answered the captain, "for Jones could get as much work out of six men as some could out of a dozen. It's worse economy to be too humane with sailors." "If that is being a smart officer I hardly think I shall become one," said I. "I'll tell you what it is, you'll never make one unless you give up some of your conscientious scruples. I must say you do very well about your work, but you're too humane a man to go to sea, and if you want to get along in this profession you've got to leave your nice principles on shore. There's no religion off soundings. The captain of a ship has got to be a liar, a cheat, a swearer, a fighter and a tyrant; in fact, if you mean to be a good mate or a good captain you've got to be a rascal." "If good principles are good for anything they are good for everything," I replied, "and if what you say is true, either this is a profession no one ought to follow or else religion is a sham and ought to be hove overboard entirely. A good God would never have imposed laws upon us which would interfere with our necessary occupations, and I don't believe he meant the Golden Rule to be confined to the shore." "That all sounds very fine," said the captain, "and perhaps you'd better knock off going to sea and set up for a parson. But you mark my words, if you go to sea, you'll have to give up your principles sooner or later, and you may as well make up your mind to it now. I've seen a good many that started as fair as you've done, but it didn't last long. But here we've got proof right alongside of us. Just look at Mr. Howard's watch there. Every time he opens his mouth you see them piling along like greased lightning, and he gets half a dozen answers for every order. But your men don't answer you half the time, and they move slower than real estate in Chelsea.
  • 65. "Now if you saw a man walking alongside of a high brick wall, and you politely asked him to step along a little faster, he'd stop and look at you; but if you told him the brick wall was tumbling down over his head you'd see how quick he'd make the dust fly. It's just so with a sailor, if you are civil to him he won't care a curse for you, but if you let him know there's something coming down on his head he'll move quick and respect you. A man didn't answer Mr. Jones once, and he just picked up the carpenter's caulking mallet and hit him over the head. He never had to speak twice to him after that." Finding the captain had got back to his favorite Mr. Jones, I thought it was of no use to prolong the talk, and it being my watch below I went to my room. Sitting down upon my chest I thought of the contrast between the captain's instructions and the teachings of home, and wondered if I must abandon the latter. It was very evident that there was not the strict discipline in the mate's watch that there was in the second mate's, and the captain's comparisons galled me; but it seemed to me that the discipline in our watch was good enough; the men did their duty well and were respectful, except that they were not always particular about answering and sometimes walked along the deck to ordinary work, whereas the second mate's men always ran, knowing that a belaying pin or stick of fire-wood would be hurled after them if they didn't. I felt the captain was right in saying that such strict discipline could not be maintained, except by working on the fears of the men, but the question with me was whether it was necessary to be so strict. Our men in a squall, or gale of wind, would be just as smart as the second mate's. It was only in ordinary and comparatively unimportant work that they were at all behind-hand, and I made up my mind that a system which necessarily required inhumanity and a sacrifice of honorable principles must be wrong, and I would have as little to do with it as possible. Opening my chest I took out a bundle of letters and selected one from my father. It was an answer to one I had written from City Point, in which I spoke of the severe discipline which was maintained on board the "Dublin," and the course which was required of the officers, and asked for advice.
  • 66. Welcome to Our Bookstore - The Ultimate Destination for Book Lovers Are you passionate about books and eager to explore new worlds of knowledge? At our website, we offer a vast collection of books that cater to every interest and age group. From classic literature to specialized publications, self-help books, and children’s stories, we have it all! Each book is a gateway to new adventures, helping you expand your knowledge and nourish your soul Experience Convenient and Enjoyable Book Shopping Our website is more than just an online bookstore—it’s a bridge connecting readers to the timeless values of culture and wisdom. With a sleek and user-friendly interface and a smart search system, you can find your favorite books quickly and easily. Enjoy special promotions, fast home delivery, and a seamless shopping experience that saves you time and enhances your love for reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebookgate.com