100% found this document useful (1 vote)
19 views

Practical UML statecharts in C C event driven programming for embedded systems 2nd Edition Miro Samek pdf download

The document is a preface for the second edition of 'Practical UML Statecharts in C/C++' by Miro Samek, which focuses on coding UML state machines in C and C++ for embedded systems. It highlights improvements made since the first edition, including new software components, enhanced efficiency, and a shift to C as the primary language of exposition. The book is intended for embedded programmers, system architects, and developers interested in event-driven programming and provides practical coding techniques rather than modeling tools.

Uploaded by

loggenpalam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
19 views

Practical UML statecharts in C C event driven programming for embedded systems 2nd Edition Miro Samek pdf download

The document is a preface for the second edition of 'Practical UML Statecharts in C/C++' by Miro Samek, which focuses on coding UML state machines in C and C++ for embedded systems. It highlights improvements made since the first edition, including new software components, enhanced efficiency, and a shift to C as the primary language of exposition. The book is intended for embedded programmers, system architects, and developers interested in event-driven programming and provides practical coding techniques rather than modeling tools.

Uploaded by

loggenpalam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Practical UML statecharts in C C event driven

programming for embedded systems 2nd Edition


Miro Samek download

https://ebookname.com/product/practical-uml-statecharts-in-c-c-
event-driven-programming-for-embedded-systems-2nd-edition-miro-
samek/

Get Instant Ebook Downloads – Browse at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Programming Embedded Systems With C and GNU Development


Tools 2nd Edition Michael Barr

https://ebookname.com/product/programming-embedded-systems-with-
c-and-gnu-development-tools-2nd-edition-michael-barr/

Test Driven Development for Embedded C 1st Edition


James W. Grenning

https://ebookname.com/product/test-driven-development-for-
embedded-c-1st-edition-james-w-grenning/

Practical C Programming 2nd Edition Steve Oualline

https://ebookname.com/product/practical-c-programming-2nd-
edition-steve-oualline/

Inhibitors of Cyclin dependent Kinases as Anti tumor


Agents Enzyme Inhibitors Series 1st Edition Paul J.
Smith

https://ebookname.com/product/inhibitors-of-cyclin-dependent-
kinases-as-anti-tumor-agents-enzyme-inhibitors-series-1st-
edition-paul-j-smith/
Recursive Macroeconomic Theory 4th Edition Lars
Ljungqvist

https://ebookname.com/product/recursive-macroeconomic-theory-4th-
edition-lars-ljungqvist/

Dying Right The Death with Dignity Movement 1st Edition


Daniel Hillyard

https://ebookname.com/product/dying-right-the-death-with-dignity-
movement-1st-edition-daniel-hillyard/

Half a Century of Music in England 1837 1887 Essays


Towards a History Francis Hueffer

https://ebookname.com/product/half-a-century-of-music-in-
england-1837-1887-essays-towards-a-history-francis-hueffer/

Engineering Wireless Based Software Systems And


Applications 1st Edition Jerry Zeyu Gao

https://ebookname.com/product/engineering-wireless-based-
software-systems-and-applications-1st-edition-jerry-zeyu-gao/

WHO Guidelines for the Management of Postpartum


Haemorrhage and Retained Placenta 1st Edition World
Health Organization

https://ebookname.com/product/who-guidelines-for-the-management-
of-postpartum-haemorrhage-and-retained-placenta-1st-edition-
world-health-organization/
Applying Wittgenstein First Edition By Rupert Read

https://ebookname.com/product/applying-wittgenstein-first-
edition-by-rupert-read/
Preface

To create a usable piece of software, you have to fight for every fix, every feature, every little
accommodation that will get one more person up the curve. There are no shortcuts. Luck is involved, but
you don’t win by being lucky, it happens because you fought for every inch.
—Dave Winer

For many years, I had been looking for a book or a magazine article that would describe
a truly practical way of coding modern state machines (UML1 statecharts) in a
mainstream programming language such as C or C++. I have never found such a
technique.
In 2002, I wrote Practical Statecharts in C/C++: Quantum Programming for
Embedded Systems (PSiCC), which was the first book to provide what had been missing
thus far: a compact, efficient, and highly maintainable implementation of UML state
machines in C and C++ with full support for hierarchical nesting of states. PSiCC was
also the first book to offer complete C and C++ source code of a generic, state machine-
based, real-time application framework for embedded systems.
To my delight, PSiCC continues to be one of the most popular books about
statecharts and event-driven programming for embedded systems. Within a year of
its publication, PSiCC was translated into Chinese, and a year later into Korean.
I’ve received and answered literally thousands of e-mails from readers who successfully
used the published code in consumer, medical, industrial, wireless, networking,
research, defense, robotics, automotive, space exploration, and many other
applications worldwide. In 2003 I started to speak about the subject matter at

1
UML stands for Unified Modeling Language and is the trademark of Object Management Group.

www.newnespress.com
xviii Preface

the Embedded Systems Conferences on both U.S. coasts. I also began to consult to
companies. All this gave me additional numerous opportunities to find out firsthand
how engineers actually use the published design techniques in a wide range of
application areas.
What you’re holding in your hands is the second edition of PSiCC. It is the direct result
of the plentiful feedback I’ve received as well as five years of the “massive parallel
testing” and scrutiny that has occurred in the trenches.

What’s New in the Second Edition?


As promised in the first edition of PSiCC, I continued to advance the code and refine
the design techniques. This completely revised second edition incorporates these
advancements as well the numerous lessons learned from readers.

New Code
First of all, this book presents an entirely new version of the software, which is now
called Quantum Platform (QP) and includes the hierarchical event processor (QEP) and
the real-time framework (QF) as well as two new components. QP underwent several
quantum leaps of improvement since the first publication six years ago. The
enhancements introduced since the first edition of PSiCC are too numerous to list here,
but the general areas of improvements include greater efficiency and testability and
better portability across different processors, compilers, and operating systems. The two
new QP components are the lightweight, preemptive, real-time kernel (QK) described
in Chapter 10 and the software-tracing instrumentation (QS) covered in Chapter 11.
Finally, I’m quite excited about the entirely new, ultralight, reduced-feature version of
QP called QP-nano that scales the approach down to the lowest-end 8- and 16-bit
MCUs. I describe QP-nano in Chapter 12.

Open Source and Dual Licensing


In 2004, I decided to release the entire QP code as open source under the terms of the
GNU General Public License (GPL) version 2, as published by the Free Software
Foundation. Independent of the open-source licensing, the QP source code is also
available under the terms of traditional commercial licenses, which expressly supersede
the GPL and are specifically designed for users interested in retaining the proprietary

www.newnespress.com
Preface xix

status of their applications based on QP. This increasingly popular strategy of


combining open source with commercial licensing, called dual licensing, is explained
in more detail in Appendix A.

C as the Primary Language of Exposition


Most of the code samples in the first edition of PSiCC pertained to the C++
implementation. However, as I found out in the field, many embedded software
developers come from a hardware background (mostly EE) and are often unnecessarily
intimidated by C++.
In this edition, I decided to exactly reverse the roles of C and C++. As before, the
companion Website contains the complete source code for both C and C++ versions.
But now, most of the code examples in the text refer to the C version, and the C++ code
is discussed only when the differences between it and the C implementation become
nontrivial and important.
As far as the C source code is concerned, I no longer use the C+ object-oriented
extension that I’ve applied and documented in the first edition. The code is still
compatible with C+, but the C+ macros are not used.

More Examples
Compared to the first edition, this book presents more examples of event-driven
systems and the examples are more complete. I made a significant effort to come up
with examples that are not utterly trivial yet don’t obscure the general principles in too
many details. I also chose examples that don’t require any specific domain knowledge,
so I don’t need to waste space and your attention explaining the problem specification.

Preemptive Multitasking Support


An event-driven infrastructure such as QP can work with a variety of concurrency
mechanisms, from a simple “superloop” to fully preemptive, priority-based
multitasking. The previous version of QP supported the simple nonpreemptive
scheduling natively but required an external RTOS to provide preemptive multitasking,
if such capability was required.
In Chapter 10, I describe the new real-time kernel (QK) component that provides
deterministic, fully preemptive, priority-based multitasking to QP. QK is a very special,

www.newnespress.com
xx Preface

super-simple, run-to-completion, single-stack kernel that perfectly matches the


universally assumed run-to-completion semantics required for state machine execution.

Testing Support
A running application built of concurrently executing state machines is a highly
structured affair where all important system interactions funnel through the event-
driven framework that ties all the state machines together. By instrumenting just this
tiny “funnel” code, you can gain unprecedented insight into the live system. In fact, the
software trace data from an instrumented event-driven framework can tell you much
more about the application than any traditional real-time operating system (RTOS)
because the framework “knows” so much more about the application.
Chapter 11 describes the new QS (“spy”) component that provides a comprehensive
software-tracing instrumentation to the QP event-driven platform. The trace data
produced by the QS component allows you to perform a live analysis of your running
real-time embedded system with minimal target system resources and without stopping
or significantly slowing down the code. Among other things, you can reconstruct
complete sequence diagrams and detailed, timestamped state machine activities for all
active objects in the system. You can monitor all event exchanges, event queues,
event pools, time events (timers), and preemptions and context switches. You can also
use QS to add your own instrumentation to the application-level code.

Ultra-Lightweight QP-nano Version


The event-driven approach with state machines scales down better than any
conventional real-time kernel or RTOS. To address really small embedded systems, a
reduced QP version called QP-nano implements a subset of features supported in QP/C
or QP/C++. QP-nano has been specifically designed to enable event-driven
programming with hierarchical state machines on low-end 8- and 16-bit
microcontrollers (MCUs), such as AVR, MSP430, 8051, PICmicro, 68HC(S)08, M16C,
and many others. Typically, QP-nano requires around 1-2KB of ROM and just a few
bytes of RAM per state machine. I describe QP-nano in Chapter 12.

Removed Quantum Metaphor


In the first edition of PSiCC, I proposed a quantum-mechanical metaphor as a way of
thinking about the event-driven software systems. Though I still believe that this

www.newnespress.com
Preface xxi

analogy is remarkably accurate, it hasn’t particularly caught on with readers, even


though providing such a metaphor is one of the key practices of eXtreme Programming
(XP) and other agile methods.
Respecting readers’ feedback, I decided to remove the quantum metaphor from this
edition. For historical reasons, the word quantum still appears in the names of the
software components, and the prefix Q is consistently used in the code for type and
function names to clearly distinguish the QP code from other code, but you don’t need
to read anything into these names.

What You Need to Use QP


Most of the code supplied with this book is highly portable C or C++, independent
of any particular CPU, operating system, or compiler. However, to focus the discussion
I provide executable examples that run in a DOS console under any variant of
Windows. I’ve chosen the legacy 16-bit DOS as a demonstration platform because it
allows programming a standard x86-based PC at the bare-metal level. Without leaving
your desktop, you can work with interrupts, directly manipulate CPU registers, and
directly access the I/O space. No other modern 32-bit development environment for the
standard PC allows this much so easily.
The additional advantage of the legacy DOS platform is the availability of mature and
free tools. To that end, I have compiled the examples with the legacy Borland Turbo
C++ 1.01 toolset, which is available for a free download from Borland.
To demonstrate modern embedded systems programming with QP, I also provide
examples for the inexpensive2 ARM Corterx-M3-based Stellaris EV-LM3S811
evaluation kit form Luminary Micro. The Cortex-M3 examples use the exact same
source code as the DOS counterparts and differ only in the board support package
(BSP). The Cortex-M3 examples require the 32KB-limited KickStart edition of the IAR
EWARM toolset, which is included in the Stellaris kit and is also available for a free
download from IAR.
Finally, some examples in this book run on Linux as well as any other POSIX-
compliant operating system such as BSD, QNX, Max OS X, or Solaris. You can also
build the Linux examples on Windows under Cygwin.

2
At the time of this writing, the EKIEV-LM3S811 kit was available for $49 (www.luminarymicro.com).

www.newnespress.com
xxii Preface

The companion Website to this book at www.quantum-leaps.com/psicc2 provides


the links for downloading all the tools used in the book, as well as other resources.
The Website also contains links to dozens of QP ports to various CPUs, operating
systems, and compilers. Keep checking this Website; new ports are added frequently.

Intended Audience
This book is intended for the following software developers interested in event-driven
programming and modern state machines:
 Embedded programmers and consultants will find a complete, ready-to-use,
event-driven infrastructure to develop applications. The book describes both
state machine coding strategies and, equally important, a compatible real-time
framework for executing concurrent state machines. These two elements are
synergistically complementary, and one cannot reach its full potential without
the other.
 Embedded developers looking for a real-time kernel or RTOS will find that the
QP event-driven platform can do everything one might expect from an RTOS
and that, in fact, QP actually contains a fully preemptive real-time kernel as
well as a simple cooperative scheduler.
 Designers of ultra low-power systems, such as wireless sensor networks, will
find how to scale down the event-driven, state machine-based approach to fit the
tiniest MCUs. The ultra-light QP-nano version (Chapter 12) combines a
hierarchical event processor, a real-time framework, and either a cooperative or
a fully preemptive kernel in just 1–2KB of ROM.
 On the opposite end of the complexity spectrum, designers of very large-scale,
massively parallel server applications will find that the event-driven approach
combined with hierarchical state machines scales up easily and is ideal for
managing very large numbers of stateful components, such as client sessions.
As it turns out, the “embedded” design philosophy of QP provides the critical
per-component efficiency both in time and space.
 The open-source community will find that QP complements other open-source
software, such as Linux or BSD. The QP port to Linux (and more generally to
POSIX-compliant operating systems) is described in Chapter 8.

www.newnespress.com
Preface xxiii

 GUI developers and computer game programmers using C or C++ will find that
QP very nicely complements GUI libraries. QP provides the high-level “screen
logic” based on hierarchical state machines, whereas the GUI libraries handle
low-level widgets and rendering of the images on the screen.
 System architects might find in QP a lightweight alternative to heavyweight
design automation tools.
 Users of design automation tools will gain deeper understanding of the inner
workings of their tools. The glimpse “under the hood” will help them use the
tools more efficiently and with greater confidence.
Due to the code-centric approach, this book will primarily appeal to software
developers tasked with creating actual, working code, as opposed to just modeling.
Many books about UML already do a good job of describing model-driven analysis
and design as well as related issues, such as software development processes and
modeling tools.
This book does not provide yet another CASE tool. Instead, this book is about practical,
manual coding techniques for hierarchical state machines and about combining state
machines into robust event-driven systems by means of a real-time framework.
To benefit from the book, you should be reasonably proficient in C or C++ and have a
general understanding of computer architectures. I am not assuming that you have
prior knowledge of UML state machines, and I introduce the underlying concepts in
a crash course in Chapter 2. I also introduce the basic real-time concepts of
multitasking, mutual exclusion, and blocking in Chapter 6.

The Companion Websites


This book has a companion Website at www.quantum-leaps.com/psicc2 that
contains the following information:
 Source code downloads for QP/C, QP/C++, and QP-nano
 All QP ports and examples described in the book
 Reference manuals for QP/C, QP/C++, and QP-nano in HTML and CHM file
formats
 Links for downloading compilers and other tools used in the book

www.newnespress.com
xxiv Preface

 Selected reviews and reader feedback


 Errata
Additionally, the Quantum Leaps Website at www.quantum-leaps.com has been
supporting the QP user community since the publication of the first edition of PSiCC in
2002. This Website offers the following resources:
 Latest QP downloads
 QP ports and development kits
 Programmer manuals
 Application notes
 Resources and goodies such as Visio stencils for drawing UML diagrams,
design patterns, links to related books and articles, and more
 Commercial licensing and technical support information
 Consulting and training in the technology
 News and events
 Discussion forum
 Newsletter
 Blog
 Links to related Websites
 And more

Finally, QP is also present on SourceForge.net—the world’s largest repository of open


source code and applications. The QP project is located at https://sourceforge.
net/projects/qpc/.

www.newnespress.com
Acknowledgments

First and foremost, I’d like to thank my wonderful family for the unfading support over
the years of creating the software and the two editions of this book.
I would also like to thank the team at Elsevier, which includes Rachel Roumeliotis and
Heather Scherer, and John (Jay) Donahue.
Finally, I’m grateful to all the software developers who contacted me with thought-
provoking questions, bug reports, and countless suggestions for improvements in the
code and documentation. As a rule, a software system only gets better if it is used and
scrutinized by many people in many different real-life projects.

www.newnespress.com
Newnes is an imprint of Elsevier
30 Corporate Drive, Suite 400, Burlington, MA 01803, USA
Linacre House, Jordan Hill, Oxford OX2 8DP, UK

Copyright # 2009, Elsevier Inc. All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or


transmitted in any form or by any means, electronic, mechanical, photocopying,
recording, or otherwise, without the prior written permission of the publisher.

Permissions may be sought directly from Elsevier’s Science & Technology Rights
Department in Oxford, UK: phone: (+44) 1865 843830, fax: (+44) 1865 853333,
E-mail: [email protected]. You may also complete your request online
via the Elsevier homepage (http://elsevier.com), by selecting “Support & Contact”
then “Copyright and Permission” and then “Obtaining Permissions.”

Library of Congress Cataloging-in-Publication Data


Application submitted.

British Library Cataloguing-in-Publication Data


A catalogue record for this book is available from the British Library.

ISBN: 978-0-7506-8706-5

For information on all Newnes publications


visit our Web site at www.elsevierdirect.com

08 09 10 11 10 9 8 7 6 5 4 3 2 1

Printed in the United States of America


Introduction

Almost all computer systems in general, and embedded systems in particular, are event-
driven, which means that they continuously wait for the occurrence of some external or
internal event such as a time tick, an arrival of a data packet, a button press, or a mouse click.
After recognizing the event, such systems react by performing the appropriate computation
that may include manipulating the hardware or generating “soft” events that trigger other
internal software components. (That’s why event-driven systems are alternatively called
reactive systems.) Once the event handling is complete, the software goes back to waiting for
the next event.
You are undoubtedly accustomed to the basic sequential control, in which a program
waits for events in various places in its execution path by either actively polling for
events or passively blocking on a semaphore or other such operating system
mechanism. Though this approach to programming event-driven systems is functional
in many situations, it doesn’t work very well when there are multiple possible
sources of events whose arrival times and order you cannot predict and where it is
important to handle the events in a timely manner. The problem is that while a
sequential program is waiting for one kind of event, it is not doing any other work and
is not responsive to other events.
Clearly, what we need is a program structure that can respond to a multitude of possible
events, any of which can arrive at unpredictable times and in an unpredictable sequence.
Though this problem is very common in embedded systems such as home appliances,
cell phones, industrial controllers, medical devices and many others, it is also very
common in modern desktop computers. Think about using a Web browser, a word
processor, or a spreadsheet. Most of these programs have a modern graphical user
interface (GUI), which is clearly capable of handling multiple events. All developers of

www.newnespress.com
xxviii Introduction

modern GUI systems, and many embedded applications, have adopted a common program
structure that elegantly solves the problem of dealing with many asynchronous events
in a timely manner. This program structure is generally called event-driven programming.

Inversion of Control
Event-driven programming requires a distinctly different way of thinking than
conventional sequential programs, such as “superloops” or tasks in a traditional RTOS.
Most modern event-driven systems are structured according to the Hollywood principle,
which means “Don’t call us, we’ll call you.” So an event-driven program is not in
control while waiting for an event; in fact, it’s not even active. Only once the event
arrives, the program is called to process the event and then it quickly relinquishes the
control again. This arrangement allows an event-driven system to wait for many events
in parallel, so the system remains responsive to all events it needs to handle.
This scheme has three important consequences. First, it implies that an event-driven
system is naturally divided into the application, which actually handles the events,
and the supervisory event-driven infrastructure, which waits for events and dispatches
them to the application. Second, the control resides in the event-driven infrastructure, so
from the application standpoint the control is inverted compared to a traditional
sequential program. And third, the event-driven application must return control after
handling each event, so the execution context cannot be preserved in the stack-based
variables and the program counter as it is in a sequential program. Instead, the
event-driven application becomes a state machine, or actually a set of collaborating
state machines that preserve the context from one event to the next in the
static variables.

The Importance of the Event-Driven Framework


The inversion of control, so typical in all event-driven systems, gives the event-driven
infrastructure all the defining characteristics of an application framework rather than
a toolkit. When you use a toolkit, such as a traditional operating system or an RTOS, you
write the main body of the application and call the toolkit code that you want to reuse.
When you use a framework, you reuse the main body and write the code it calls.
Another important point is that an event-driven framework is actually necessary if you
want to combine multiple event-driven state machines into systems. It really takes more
than “just” an API, such as a traditional RTOS, to execute concurrent state machines.

www.newnespress.com
Introduction xxix

State machines require an infrastructure (framework) that provides, at a minimum,


run-to-completion (RTC) execution context for each state machine, queuing of events,
and event-based timing services. This is really the pivotal point. State machines cannot
operate in a vacuum and are not really practical without an event-driven framework.

Active Object Computing Model


This book brings together two most effective techniques of decomposing event-driven
systems: hierarchical state machines and an event-driven framework. The combination
of these two elements is known as the active object computing model. The term active
object comes from the UML and denotes an autonomous object engaging other
active objects asynchronously via events. The UML further proposes the UML variant
of statecharts with which to model the behavior of event-driven active objects.
In this book, active objects are implemented by means of the event-driven framework
called QF, which is the main component of the QP event-driven platform. The QF
framework orderly executes active objects and handles all the details of thread-safe
event exchange and processing within active objects. QF guarantees the universally
assumed RTC semantics of state machine execution, by queuing events and dispatching
them sequentially (one at a time) to the internal state machines of active objects.
The fundamental concepts of hierarchical state machines combined with an event-
driven framework are not new. In fact, they have been in widespread use for at least two
decades. Virtually all commercially successful design automation tools on the market
today are based on hierarchical state machines (statecharts) and incorporate internally a
variant of an event-driven, real-time framework similar to QF.

The Code-Centric Approach


The approach I assume in this book is code-centric, minimalist, and low-level. This
characterization is not pejorative; it simply means that you’ll learn how to map
hierarchical state machines and active objects directly to C or C++ source code, without
big tools. The issue here is not a tool—the issue is understanding.
The modern design automation tools are truly powerful, but they are not for everyone.
For many developers the tool simply can’t pull its own weight and gets abandoned. For
such developers, the code-centric approach presented in this book can provide a
lightweight alternative to the heavyweight tools.

www.newnespress.com
xxx Introduction

Most important, though, no tool can replace conceptual understanding. For example,
determining which exit and entry actions fire in which sequence in a nontrivial state
transition is not something you should discover by running a tool-supported animation
of your state machine. The answer should come from your understanding of the
underlying state machine implementation (discussed in Chapters 3 and 4). Even if
you later decide to use a design automation tool and even if that particular tool would
use a different statechart implementation technique than discussed in this book, you
will still apply the concepts with greater confidence and more efficiency because of
your understanding of the fundamental mechanisms at a low level.
In spite of many pressures from existing users, I persisted in keeping the QP event-
driven platform lean by directly implementing only the essential elements of the bulky
UML specification and supporting the niceties as design patterns. Keeping the core
implementation small and simple has real benefits. Programmers can learn and deploy
QP quickly without large investments in tools and training. They can easily adapt
and customize the framework’s source code to the particular situation, including
to severely resource-constrained embedded systems. They can understand, and indeed
regularly use, all the provided features.

Focus on Real-Life Problems


You can’t just look at state machines and the event-driven framework as a collection of
features, because some of the features will make no sense in isolation. You can only use
these powerful concepts effectively if you are thinking about design, not simply coding.
And to understand state machines that way, you must understand the problems with
event-driven programming in general.
This book discusses event-driven programming problems, why they are problems,
and how state machines and active object computing model can help. Thus, I begin
most chapters with the programming problems the chapter will address. In this way,
I hope to move you, a little at a time, to the point where hierarchical state machines
and the event-driven framework become a much more natural way of solving the
problems than the traditional approaches such as deeply nested IFs and ELSEs for
coding stateful behavior or passing events via semaphores or event flags of a
traditional RTOS.

www.newnespress.com
Introduction xxxi

Object Orientation
Even though I use C as the primary programming language, I also extensively use
object-oriented design principles. Like virtually all application frameworks, QP uses the
basic concepts of encapsulation (classes) and single inheritance as the primary
mechanisms of customizing, specializing, and extending the framework to a particular
application. Don’t worry if these concepts are new to you, especially in C. At the C
language level, encapsulation and inheritance become just simple coding idioms, which
I introduce in Chapter 1. I specifically avoid polymorphism in the C version
because implementing late binding in C is a little more involved. Of course, the C++
version uses classes and inheritance directly and QP/C++ applications can use
polymorphism.

More Fun
When you start using the techniques described in this book, your problems will change.
You will no longer struggle with 15 levels of convoluted if–else statements, and you
will stop worrying about semaphores or other such low-level RTOS mechanisms.
Instead, you’ll start thinking at a higher level of abstraction about state machines,
events, and active objects. After you experience this quantum leap you will find,
as I did, that programming can be much more fun. You will never want to go back to
the “spaghetti” code or the raw RTOS.

How to Contact Me
If you have comments or questions about this book, the code, or event-driven
programming in general, I’d be pleased to hear from you. Please e-mail me at
[email protected].

www.newnespress.com
www.CartoonStock.com

PART I UML STATE MACHINES


State machines are the best-known formalism for specifying and implementing event-
driven systems that must react to incoming events in a timely fashion. The advanced
UML state machines represent the current state of the art in state machine theory
and notation.
Part I of this book shows practical ways of using UML state machines in event-driven
applications to help you produce efficient and maintainable software with well-
understood behavior, rather than creating “spaghetti” code littered with convoluted IFs
and ELSEs. Chapter 1 presents an overview of the method based on a working example.

www.newnespress.com
2 Part I

Chapter 2 introduces state machine concepts and the UML notation. Chapter 3 shows
the standard techniques of coding state machines, and Chapter 4 describes a generic
hierarchical event processor. Part I concludes with Chapter 5, which presents a mini-
catalogue of five state design patterns. You will learn that UML state machines are a
powerful design method that you can use, even without complex code-synthesizing
tools.

www.newnespress.com
CHAPTER 1

Getting Started with UML State


Machines and Event-Driven
Programming

It is common sense to take a method and try it. If it fails, admit it frankly and try another. But above all,
try something.
—Franklin D. Roosevelt

This chapter presents an example project implemented entirely with UML state
machines and the event-driven paradigm. The example application is an interactive
“Fly ‘n’ Shoot”-type game, which I decided to include early in the book so that you can
start playing (literally) with the code as soon as possible. My aim in this chapter is
to show the essential elements of the method in a real, nontrivial program, but without
getting bogged down in details, rules, and exceptions. At this point, I am not trying
to be complete or even precise, although this example as well as all other examples in
the book is meant to show a good design and the recommended coding style. I don’t
assume that you know much about UML state machines, UML notation, or event-driven
programming. I will either briefly introduce the concepts, as needed, or refer you to
the later chapters of the book for more details.
The example “Fly ‘n’ Shoot” game is based on the Quickstart application provided in source
code with the Stellaris EV-LM3S811 evaluation kit from Luminary Micro [Luminary 06].
I was trying to make the “Fly ‘n’ Shoot” example behave quite similarly to the original
Luminary Micro Quickstart application so that you can directly compare the event-driven
approach with the traditional solution to essentially the same problem specification.

www.newnespress.com
4 Chapter 1

1.1 Installing the Accompanying Code


The companion Website to this book at www.quantum-leaps.com/psicc2 contains the
self-extracting archive with the complete source code of the QP event-driven platform
and all executable examples described in this book; as well as documentation,
development tools, resources, and more. You can uncompress the archive into any
directory. The installation directory you choose will be referred henceforth as the QP
Root Directory <qp>.

NOTE
Although in the text I mostly concentrate on the C implementation, the accompanying Web-
site also contains the equivalent C++ version of virtually every element available in C. The
C++ code is organized in exactly the same directory tree as the corresponding C code, except
you need to look in the <qp>\qpcpp\. . . directory branch.

Specifically to the “Fly ‘n’ Shoot” example, the companion code contains two versions1
of the game. I provide a DOS version for the standard Windows-based PC (see
Figure 1.1) so that you don’t need any special embedded board to play the game and
experiment with the code.

NOTE
I’ve chosen the legacy 16-bit DOS platform because it allows programming a standard PC at
the bare-metal level. Without leaving your desktop, you can work with interrupts, directly
manipulate CPU registers, and directly access the I/O space. No other modern 32-bit devel-
opment environment for the standard PC allows this much so easily. The ubiquitous PC run-
ning under DOS (or a DOS console within any variant of Windows) is as close as it gets to
emulating embedded software development on the commodity 80x86 hardware. Addition-
ally, you can use free, mature tools, such as the Borland C/C++ compiler.

I also provide an embedded version for the inexpensive2 ARM Cortex-M3-based


Stellaris EV-LM3S811 evaluation kit (see Figure 1.2). Both the PC and Cortex-M3

1
The accompanying code actually contains many more versions of the “Fly ‘n’ Shoot” game, but they are
not relevant at this point.
2
At the time of this writing the EV-LM3S811 kit was available for $49 (www.luminarymicro.com).

www.newnespress.com
Getting Started with UML State Machines and Event-Driven Programming 5

versions use the exact same source code for all application components and differ only
in the Board Support Package (BSP).

1.2 Let’s Play


The following description of the “Fly ‘n’ Shoot” game serves the dual purpose of
explaining how to play the game and as the problem specification for the purpose of
designing and implementing the software later in the chapter. To accomplish these two
goals I need to be quite detailed, so please bear with me.
Your objective in the game is to navigate a spaceship through an endless horizontal
tunnel with mines. Any collision with the tunnel or the mine destroys the ship. You can
move the ship up and down with Up-arrow and Down-arrow keys on the PC (see
Figure 1.1) or via the potentiometer wheel on the EV-LM3S811 board (see Figure 1.2).
You can also fire a missile to destroy the mines in the tunnel by pressing the Spacebar
on the PC or the User button on the EV-LM3S811 board. Score accumulates for
survival (at the rate of 30 points per second) and destroying the mines. The game lasts
for only one ship.
The game starts in a demo mode, where the tunnel walls scroll at the normal pace
from right to left and the “Press Button” text flashes in the middle of the screen.
You need to generate the “fire missile” event for the game to begin (press Spacebar
on the PC or the User button on the EV-LM3S811 board).
You can have only one missile in flight at a time, so trying to fire a missile while it is
already flying has no effect. Hitting the tunnel wall with the missile brings you no
points, but you earn extra points for destroying the mines.
The game has two types of mines with different behavior. In the original Luminary
Quickstart application both types of mines behave the same, but I wanted to
demonstrate how state machines can elegantly handle differently behaving mines.
Mine type 1 is small, but can be destroyed by hitting any of its pixels with the missile.
You earn 25 points for destroying a mine type 1. Mine type 2 is bigger but is nastier
in that the missile can destroy it only by hitting its center, not any of the “tentacles.”
Of course, the ship is vulnerable to the whole mine. You earn 45 points for destroying
a mine type 2.
When you crash the ship, by either hitting a wall or a mine, the game ends and displays
the flashing “Game Over” text as well as your final score. After 5 seconds of flashing,

www.newnespress.com
6 Chapter 1

the “Game Over” screen changes back to the demo screen, where the game waits to be
started again.
Additionally the application contains a screen saver because the OLED display of the
original EV-LM3S811 board has burn-in characteristics similar to a CRT. The screen
saver only becomes active if 20 seconds elapse in the demo mode without starting
the game (i.e., the screen saver never appears during game play). The screen saver is
a simple random pixel type rather than the “Game of Life” algorithm used in the
original Luminary Quickstart application. I’ve decided to simplify this aspect of the
implementation because the more elaborate pixel-mixing algorithm does not contribute
any new or interesting behavior.
After a minute of running the screen saver, the display turns blank and only a single
random pixel shows on the screen. Again, this is a little different from the original
Quickstart application, which instead blanks the screen and starts flashing the User
LED. I’ve changed this behavior because I have a better purpose for the User LED (to
visualize the activity of the idle loop).

Mine Mine Tunnel


Ship Missile Type 1 Explosion Type 2 wall

Figure 1.1: The “Fly ‘n’ Shoot” game running in a DOS window under Windows XP.

www.newnespress.com
Getting Started with UML State Machines and Event-Driven Programming 7

Potentiometer Reset LM3S811 96 x 16 Power


Wheel Switch Cortex-M3 MCU OLED Display LED

USB Cable LMI FTDI User User


to PC Debugger LED Switch

Figure 1.2: The “Fly ‘n’ Shoot” game running on the Stellaris EV-LM3S811
evaluation board.

1.2.1 Running the DOS Version


The “Fly ‘n’ Shoot” sample code for the DOS version (in C) is located in the
<qp>\qpc\examples\80x86\dos\tcpp101\l\game\ directory, where <qp> stands
for the installation directory in which you chose to install the accompanying software.
The compiled executable is provided, so you can run the game on any Windows-based
PC by simply double-clicking the executable game.exe located in the directory
<qp>\qpc\examples\80x86\dos\tcpp101\l\game\dbg\. The first screen you
see is the game running in the demo mode with the text “Push Button” flashing in
the middle of the display. At the top of the display you see a legend of keystrokes
recognized by the application. You need to hit the SPACEBAR to start playing the game.
Press the ESC key to cleanly exit the application.
If you run “Fly ‘n’ Shoot” in a window under Microsoft Windows, the animation effects in
the game might appear a little jumpy, especially compared to the Stellaris version of the
same game. You can make the application execute significantly more smoothly if you
switch to the full-screen mode by pressing and holding the Alt key and then pressing the
Enter key. You go back to the window mode via the same Alt-Enter key combination.

As you can see in Figure 1.1, the DOS version uses simply the standard VGA text mode
to emulate the OLED display of the EV-LM3S811 board. The lower part of the DOS screen

www.newnespress.com
8 Chapter 1

is used as a matrix of 80  16 character-wide “pixels,” which is a little less than the 96  16


pixels of the OLED display but still good enough to play the game. I specifically avoid
employing any fancier graphics in this early example because I have bigger fish to fry for
you than to worry about the irrelevant complexities of programming graphics.
My main goal is to make it easy for you to understand the event-driven code and
experiment with it. To this end, I chose the legacy Borland Turbo C++ 1.01 toolset to
build this example as well as several other examples in this book. Even though Turbo
C++ 1.01 is an older compiler, it is adequate to demonstrate all features of both the
C and C++ versions. Best of all, it is available for a free download from the Borland
“Museum” at http://bdn.borland.com/article/0,1410,21751,00.html.
The toolset is very easy to install. After you download the Turbo C++ 1.01 files directly
from Borland, you need to unzip the files onto your hard drive. Then you run the
INSTALL.EXE program and follow the installation instructions it provides.

NOTE
I strongly recommend that you install the Turbo C++ 1.01 toolset into the directory
C:\tools\tcpp101\. That way you will be able to directly use the provided project files
and make scripts.

Perhaps the easiest way to experiment with the “Fly ‘n’ Shoot” code is to launch the Turbo
C++ IDE (TC.EXE) and open the provided project file GAME-DBG.PRJ, which is located
in the directory <qp>\qpc\examples\80x86\dos\tcpp101\l\game\. You can
modify, recompile, execute, and debug the program directly from the IDE. However, you
should avoid terminating the program stopped in the debugger, because this will not restore
the standard DOS interrupt vectors for the time tick and keyboard interrupts. You should
always cleanly exit the application by letting it freely run and pressing the Esc key.
The next section briefly describes how to run the embedded version of the game. If you
are not interested in the Cortex-M3 version, feel free to skip to Section 1.3, where I start
explaining the application code.

1.2.2 Running the Stellaris Version


In contrast to the “Fly ‘n’ Shoot” version for DOS running in the ancient real mode of
the 80x86 processor, the exact same source code runs on one of the most modern
processors in the industry: the ARM Cortex-M3.

www.newnespress.com
Getting Started with UML State Machines and Event-Driven Programming 9

The sample code for the Stellaris EV-LM3S811 board is located in the
<qp>\qpc\examples\cortex-m3\vanilla\iar\game-ev-lm3s811\ directory,
where <qp> stands for the root directory in which you chose to install the
accompanying software.
The code for the Stellaris kit has been compiled with the 32KB-limited Kickstart edition
of the IAR Embedded Workbench for ARM (IAR EWARM) v 5.11, which is provided
with the Stellaris EV-LM3S811 kit. You can also download this software free of charge
directly from IAR Systems (www.iar.com)after filling out an online registration.
The installation of IAR EWARM is quite straightforward, since the software comes
with the installation utility. You also need to install the USB drivers for the hardware
debugger built into the EV-LM3S811 board, as described in the documentation of
the Stellaris EV-LM3S811 kit.

NOTE
I strongly recommend that you install the IAR EWARM toolset into the directory C:\tools
\iar\arm_ks_5.11. That way you will be able to directly use the provided EWARM work-
space files and make scripts.

Before you program the “Fly ‘n’ Shoot” game to the EV-LM3S811 board, you might
want to play a little with the original Quickstart application that comes preprogrammed
with the EV-LM3S811 kit.
To program the “Fly ‘n’ Shoot” game to the Flash memory of the EV-LM3S811 board,
you first connect the EV-LM3S811 board to your PC with the USB cable provided in the
kit and make sure that the Power LED is on (see Figure 1.2). Next, you need to launch the
IAR Embedded Workbench and open the workspace game-ev-lm3s811.eww located
in the <qp>\qpc\examples\cortex-m3\vanilla\iar\game-ev-lm3s811\
directory. At this point your screen should look similar to the screenshot shown in
Figure 1.3.
The game-ev-lm3s811 project is set up to use the LMI FTDI debugger, which is the
piece of hardware integrated on the EV-LM3S811 board (see Figure 1.2). You can
verify this setup by opening the “Options” dialog box via the Project | Options menu.
Within the “Options” dialog box, you need to select the Debugger category in the panel
on the left. While you’re at it, you could also verify that the Flash loading is enabled
by selecting the “Download” tab. The checked “Use flash loader(s)” check box means

www.newnespress.com
Exploring the Variety of Random
Documents with Different Content
The Project Gutenberg eBook of The Angel
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

Title: The Angel

Author: Guy Thorne

Release date: August 24, 2012 [eBook #40571]


Most recently updated: October 23, 2024

Language: English

Credits: Produced by Mark C. Orton, Mary Meehan and the


Online
Distributed Proofreading Team at http://www.pgdp.net
(This
book was produced from scanned images of public
domain
material from the Google Print project.)

*** START OF THE PROJECT GUTENBERG EBOOK THE ANGEL ***


THE ANGEL
BY GUY THORNE
Author of "When It Was Dark," "Made in His
Image," "First It Was Ordained," Etc.
G. W. DILLINGHAM COMPANY
PUBLISHERS NEW YORK
Copyright, 1908, by
G. W. DILLINGHAM COMPANY
PREFACE
I do not think a book of this sort requires a very lengthy foreword,
but one or two things I feel it necessary to say concerning it. In the
first place, I have to thank Mr. Hamilton Edwards for many valuable
suggestions concerning it, suggestions which, undoubtedly, helped
me very much in the writing.
The story is an attempt to impress upon readers the fact that we
are, without doubt, surrounded on our way through life by unseen
presences, unseen intelligences, which guard or attack that real
portion of us which is ourselves—the soul.
Superficially, but only superficially, this is a very material age. We are
surrounded by so many material wonders that the unthinking person
is inclined to believe, at any rate to state, that the material is
everything. Yet there is nothing more unsatisfying than the purely
material aspect of life, after all.
How can any one be surprised if the ordinary man is perplexed when
he is called upon to decide questions of economy and morality, when
the material point of view is all that he can see? For all questions of
morality must necessarily depend—as long ago Plato pointed out—
upon a belief in something which we cannot touch or see.
Otherwise, morality has no significance and no meaning, except that
of expediency.
If, when our body dies, our personality stops, then I can see no
logical reason whatever for trying to be good. To get all this life in
itself has to offer by means of any sort—provided they do not entail
personal discomfort—is the logical philosophy of the materialist. Yet
the materialist, at the same time, is very frequently an honest and
good-living man. This is not because he is a materialist, for there is
no reason for being honest, unless one is found out in one's
dishonesty, but because there is implanted within that soul which he
denies a spark of the Divine Fire.
Of course, amongst thinking and really educated men and women,
materialism is as out-moded as the bow and arrow in modern
warfare, yet the majority of people do not think very much, nor are
they well educated.
This story is an endeavour to point out that people who assert
nowadays that Matthew Arnold's dogma, "miracles do not happen,"
are hopelessly out of the run of modern thought.
Men like Sir Oliver Lodge are laboriously discovering some of the
laws of the Universe which give us portents and signs. No one who
knows to-day dares to sneer at parthenogenesis, or to repeat the
slander of Celsus about the Mother of God. It is only men who do
not know, and men who have grown rusty in reposing on their past
reputations, who cannot see that Materialism as a philosophy is
dead.
Day by day fresh evidence of the power of the Spirit over Matter
bursts upon us. A plea for "philosophic doubt," for Professor Huxley's
infallibility, is no longer necessary. The very distinction between
Matter and Spirit grows more and more difficult as Science develops
analytical power. The minds of men are being again prepared to
receive that supreme revelation which told of the wedding of the
earth and Heaven, the taking of the Manhood into God.
The processes by which the hero of this story—Joseph—became
what he was have been carefully thought out, in order to provide an
opportunity for those who read the story, to get near to the
explanation of some of those psychical truths which need not
necessarily be supernatural, but only supernormal. It seems to me
the wildest of folly to say that because a thing is not capable of
being explained by the laws of Nature as we know them, that it is
above the laws of Nature. Every week is a witness to the fact that
the laws of Nature are only imperfectly known by us, and therefore,
to say that anything is outside Nature is, to put it plainly, simply
nonsense.
For Nature does not exist, nor is there any possibility that it has ever
existed, without a Controlling Power which created it.
At the very end of his famous and wonderful life, Lord Kelvin himself
stated it as his unalterable opinion, after all the investigations he had
made into the primary causes of phenomena as we know them, that
the only possible explanation was that a Controlling Intelligence
animated and produced them all.
I was reading a few days ago one of a series of weekly articles
which an eminent modern scientist, Sir Ray Lankester, is writing in a
famous newspaper. He was speaking of Darwin and "The Origin of
Species," and he seemed to imagine that the great discovery of
Darwin finally disposed of the truth of the first chapter of Genesis, as
we have it in the pages of the Holy Bible. Surely nothing was ever
more limited than such a view as this! God manifests Himself in His
own way, at His own time, and in a fashion which is modified and
adjusted to the intelligences and opportunities of those who live at
the time of this or that Revelation in the progressive scheme of
Revelation itself. To say that because modern science has proved
that God did not, as a human potter or modeller of clay would do,
make the whole of living things in full being, and at a definite time,
that therefore the Bible is untrue, is simply the blindness of those
who do not realize that Truth must often wear a robe to hide its
glory from the eyes of those who are unable to appreciate its full
splendour and magnificence.
If we are descended or evolved from primeval protoplasm, as I for
one am quite prepared to believe, one simply goes back to the
simple question—"Who made the protoplasm?"
It is no use. We cannot get away, try as we will, from the fact of
God, and we cannot also get away from the fact of the Incarnation,
when God revealed Himself more fully than ever before, and when
God Himself became Man.
My idea in this story is to show that, by means of processes of which
we have at present but little idea, a man may be drained and
emptied, under special circumstances, of himself and the influences
of his past life, and be made as a vessel for the special in-pouring of
the Holy Spirit.
The death of Lluellyn Lys for Joseph, the mysterious interplay of a
soul going, and meeting on its way, another soul about to go into
the Unknown, aided by the special dispensation of God, might, I
think, well produce some such supernormal being as the Joseph of
this tale. Perhaps an angel, one of those mysterious beings—whom
Christians believe to be the forces and the messengers of God—may
have animated Joseph in his mission, without entirely destroying or
obscuring his personality. Be this as it may, I offer this story as an
effort to attract my readers' minds towards a consideration of the
Unseen which is all around us, and which—more probably than not—
is the real world, after all, and one in which we, as we are now, walk
as phantoms and simulacrums of what we shall one day be in the
glorious hereafter.
GUY THORNE.
The Angel
CHAPTER I
AND GOD SPAKE——
Two men stood outside a bird-fancier's shop in the East End of
London. The shop was not far from the docks, and had a great
traffic with sailors. Tiny emerald and gamboge love-birds squawked
in their cages, there was a glass box of lizards with eyes like live
rubies set in the shop window, while a hideous little ape—chained to
a hook—clattered in an impish frenzy.
Outside the shop door hung a cage containing a huge parrot, and it
was this at which the two men were looking.
Hampson, a little wrinkled man in very shabby clothes, but of a
brave and confident aspect, pointed to the parrot.
"I wonder if it talks?" he said.
Immediately upon his words the grey bird, its watchful eye gleaming
with mischievous fire, began a stream of disconnected words and
sentences, very voluble, very rapid, and very clear.
Hampson shuddered.
"Do you know, Joseph," he said, "I am always afraid when I hear
that sound—that noise of a bird talking human words. To me, there
is no more dreadful sound in the world."
Hampson's companion, a taller and much more considerable man,
looked at the little fellow with surprise.
"Afraid?" he said. "Why should you be afraid? The sound is
grotesque, and nothing more. Has hunger completed her work, and
privation conquered at last? Are your nerves going?"
"Never better, my dear Joseph," the little man replied cheerfully. "It
will take a long time to knock me out. It's you I'm afraid about. But
to return to the parrot. Has it ever struck you that in all nature the
voice of a bird that has been taught to speak is unique? There is no
other sound even remotely resembling it. We hear a voice using
human words, and, in this instance, and this alone, we hear the
spoken words of a thing that has no soul!"
The other man started.
"How fantastic you are," he said impatiently. "The thing has a brain,
hasn't it? You have in a larger and far more developed measure
exactly what that bird has; so have I. But that is all. Soul! There is
no such thing!"
The bird in the cage had caught the word, which excited its
mechanical and oral memory to the repetition of one of its stock
phrases.
"Soul! Soul! 'Pon my soul, that's too good. Ha, ha, ha!" said the
parrot.
"Polly differs, apparently," Hampson said drily, as they moved on
down the Commercial Road; "but what a hopeless materialist you
are, Joseph. You go back to the dogmatism of the pre-Socratic
philosophers or voice the drab materialism of the modern animal
man who thinks with his skin. Yet you've read your Plato!—you
observe that I carefully refrain from bringing in Christian philosophy
even! You believe in nothing that you have not touched or handled.
Because you can't find the soul at a post-mortem examination of the
body you at once go and say there is no such thing. Scholars and
men of science like you seem astonishingly blind to the value of
evidence when it comes to religious matters. You, my dear Joseph,
have never seen India. Yet you know a place called India exists. How
do you know it? Simply through the evidence of other people who
have been there. You have just as much right to tell the captain of a
P. & O. steamer that what he thought was Calcutta was merely a
delusion as to tell me or any other professing Christian that there is
no such thing as the Kingdom of Heaven! Well, I must be off; I have
a bit of work to do that may bring in a few shillings. There may be
dinner to-night, Joseph!"
With a quick smile, Hampson turned down a side street and was
gone. The man called Joseph continued his way, walking slowly and
listlessly, his head sunk upon his breast in thought.
The teeming life of the great artery of East London went on all
round him; but he saw nothing of it. A Chinaman, with a yellow,
wrinkled face, jostled up against him, and he did not know it; a
bloated girl, in a stained plush blouse, wine-coloured like her face,
and with an immense necklace of false pearls, coughed out some
witticism as he passed; a hooligan surveyed him at leisure, decided
that there could be nothing worth stealing upon him, and strolled
away whistling a popular tune—one and all were no more to the
wanderer than a dream, some dream dim-panelled upon the painted
scenes of sleep.
Shabbily dressed as he was, there was yet something about the man
which attracted attention. He drew the eye. He was quite unlike any
one else. One could not say of him, "Here is an Englishman," or
"There is a German." He would have looked like a foreigner—
something alien from the crowd—in any country to which he went.
Joseph's age was probably about thirty-three, but time and sorrow
had etched and graven upon his face a record of harsh experience
which made him seem much older.
The cheeks were gashed and furrowed with thought. Looking
carefully at him, one would have discovered that he was a distinctly
handsome man. The mouth was strong and manly in its curves,
though there was something gentle and compassionate in it also.
The nose was Greek, straight and clearly cut; the hair thick, and of a
dark reddish-brown. But the wonder of the man's face lay in his
eyes. These were large and lustrous; full of changing light in their
dark and almost Eastern depth. They were those rare eyes which
seem to be lit up from within as if illuminated by the lamp of the
soul.
Soul! Yes, it was that of which those eyes told in an extraordinary
and almost overwhelming measure.
The soul is not a sort of fixed essence, as people are apt to forget. It
is a fluid thing, and expands or contracts according to the life of its
owner. We do not, for example, see any soul in the eyes of a gross,
over-fed, and sensual man. Yet this very man in the Commercial
Road, who denied the very existence of the soul with convinced and
impatient mockery, was himself, in appearance, at any rate, one of
those rare beings of whom we say, "That man is all soul."
The man's full name was Joseph Bethune. To the tiny circle of his
friends and acquaintances he was simply Joseph. If they had ever
known his surname, they had forgotten it. He was one of those men
who are always called by their Christian names because, whatever
their circumstances may be, they are real, accepted, and
unquestioned facts in the lives of their friends.
Joseph Bethune's history, to which he never referred, had been, up
to the present, drab, monotonous, and dismal. When an event had
occurred it was another failure, and he could point to no red-letter
days in his career. Joseph had never known either father or mother.
Both had died during his infancy, leaving him in the care of
guardians.
His father had been a pastor of the Methodist sect—a man of
singular holiness of life and deep spiritual fervour. Possessed of some
private means, he had been able to leave a sufficient sum for his
son's education upon a generous and liberal scale.
The boy's guardians were distant relatives in each case. One was a
clergyman, the other a prosperous London solicitor. The strange,
studious child, quiet, dreamy, and devoted to his books, found
himself out of touch with both.
The clergyman was a Low Churchman, but of the worst type. There
was nothing of the tolerant outlook and strong evangelical piety of a
Robertson in Mr. St. John. He was as narrow as his creed,
condemning all that he had not experienced, or could not
understand, hating the devil more than he loved God. If he had been
sent to the rack he could not have truthfully confessed to an original
thought.
Joseph Bethune was sent to an English public school of good,
though not of first, rank. Here he was unpopular, and made no
friends. His nature was too strong, and, even as a boy, his
personality too striking, for him to experience any actual physical
discomfort from his unpopularity. He was never bullied, and no one
interfered with him; but he remained utterly lonely.
In contradiction of the usual custom in the English public school of
his day, Hamilton possessed splendid laboratories, and great
attention was paid to modern science and mathematics.
Of these advantages Joseph Bethune availed himself to the full. His
temper of mind was accurate and inquiring, and though his manner
was dreamy and abstracted, it was the romance of science over
which he pored; the cold, glacial heights of the higher mathematics
among which his imagination roamed.
He gained a scholarship at Cambridge, lived a retired and
monotonous life of work, shunning the natural and innocent
amusements of youth while at the university, and was bracketed
Third Wrangler as a result of his degree examination.
By this time his moderate patrimony was nearly exhausted, though,
of course, his success in the schools had placed many lucrative posts
within his reach. He had actually been offered a fellowship and a
tutorial post at his own college, when he wrecked his university
career by an extraordinary and quite unexpected proceeding.
At a great meeting in the Corn Exchange, convened by the Bishop of
London for a discussion of certain vexed questions of the Christian
faith, Joseph Bethune rose, and, in a speech of some fifteen
minutes' duration, delivered an impassioned condemnation of
Christianity, concluding with a fierce avowal of his disbelief in God,
and in anything but the purely material.
We are tolerant enough nowadays. The red horror of the Inquisition
has departed, and men are no longer "clothed in a shirt of living fire"
for a chance word. A "Protestant" ruler no longer hangs the priests
of the Italian Mission for saying the Mass. Any one is at liberty to
believe what he pleases. But men about to occupy official positions
must not bawl unadulterated atheism from the housetops.
The offence was too flagrant, the offer of the fellowship was
withdrawn, and Joseph, so far as Cambridge was concerned, was
ruined.
It is perfectly true that there were many people who believed exactly
as he did. They sympathized with him, but in secret, and no word or
hint of their sympathy ever reached him. He had done the
unpardonable thing: he had dared to speak out his thoughts, and
men of the world do not care to champion openly one who is
publicly disgraced.
The news got about in many quarters. The man was not an
"agnostic"—polite and windy word! But he was an atheist! Terrible
word, recalling shuddering memories of Tom Paine and Bradlaugh
even in the minds of men and women who themselves believed in
nothing at all. Some men would have only been locally harmed by
such an episode as this. But Bethune's case was peculiar, and it
ruined him.
He had nothing to sell in any market but the academic. He was a
born lecturer; demonstrator of scientific truth. But he had just
overstepped the limit allowed in even these liberal times. Moreover,
he was too young. Such a speech as he had made, had it been
delivered at sixty, with a long and distinguished record behind the
speaker, would have been regarded as a valuable and interesting
contribution to modern thought. It might even have been taken as a
sort of fifth Gospel—the Gospel according to St. Thomas the
Doubter!
Joseph, however, was done for.
He disappeared from the university. His name was no more heard,
and after the traditional nine days was utterly forgotten.
It is true that three or four men who saw further than their fellows
realized that a force, a potential but very real force, had departed.
Some one who, as they believed, was to have done extraordinary
things was now crushed and robbed of his power. They perceived
that virtue had departed from the intellectual garment that shelters
the men who can!
Joseph tried, and tried in vain, to make such a living as his vast
mental acquirements and achievements entitled him to. Obscure
tutorships, ill-paid lecturing to coteries of cock-cure Socialists, who
believed in nothing but their chances of getting a slice of the wealth
of men who had worked, and not merely talked—these were his
dismal and pitiful endeavours.
He came at last to the very lowest pitch of all. He, the high wrangler,
the eminent young mathematician, earned a squalid and horribly
precarious living by teaching elementary science to the sons of
struggling East End shopkeepers who were ambitious of County
Council scholarships for their progeny.
His health was impaired, but his spirit was as a reed bruised and
shaken by the winds of adversity, yet not broken. He had known
sorrow, was acquainted with grief.
He had plumbed the depths of poverty, and his body was a wreck.
Want of food—the mean and squalid resting-places he had perforce
to seek—the degradation and vileness of his surroundings, had
sapped the life blood. He did not know the defiant trumpet words of
a poet of our time, but had he done so, they would have well
expressed his attitude—

Out of the night that covers me,


Black as the pit from pole to pole,
I thank whatever gods may be
For my unconquerable soul.
In the fell clutch of circumstance
I have not winced nor cried aloud;
Under the bludgeonings of chance
My head is bloody but unbowed.

He turned off into a by-street, and walked on till he came to the


docks. His progress was quite aimless. Once he stopped and wearily
asked himself whither he was going; but the next moment he was
lost in thought, and moved on again.
Once he stumbled over a steel hawser. He nearly lost his balance,
and had his arm not shot out with an involuntary movement to
clutch the bollard on his left, he would have fallen over the granite-
bound edge of the wharf into the foul, black, slimy depths below.
Hardly giving a thought to the danger he had just escaped, he
moved on and on.
Through open sheds—where freight was heaped up waiting the
onslaught of stevedores and labourers—across jutting portions of
cobbled space and shunting grounds, he came to a remote corner,
far removed from the rattle of cranes and the shouts of the
workmen.
Something drew him out of himself, and fixed his attention. It was a
shadow. It caught his gaze, and his eyes became fixed on it. He
knew that a shadow was only the phenomenon produced when
streams of radiant energy are intercepted by an object which is
unable to transmit them. His scientific training had taught him that
even sound shadows may be produced, though to recognize the
existence of them the ear must pass from the unshadowed to the
shadowed part. Perhaps it was a symbol! He himself was in darkness
and shadow. Would his ear ever catch those mysterious harmonies
that come to those who suffer?—Hampson heard them....
A woman crept stealthily behind the wall, and the shadow
disappeared.
The woman bore a burden; what it was he could not see. But she
held it close to her breast with the tense clasp of some fierce
emotion.
She had not noticed the dreamer. She stopped by some steps
leading down to the waters of a small section of the dock.
Joseph sat down on a capstan and looked steadily at her.
The woman unclasped the burden she bore, drew aside a part of the
covering, and kissed—a baby face. He knew at once what she was
doing. She was bidding it good-bye. She was going to drown it.
"And they say that there is a God," Joseph thought. "A conscious
Intelligence that directs human affairs. Even Lord Kelvin himself
thought so! Yet God does nothing to save this woman from her sin—
or rather crime!"
He gazed fiercely. Those eyes, through which his rebellious
unconquerable soul shone out, caught the startled stare of the
woman as she saw the strange man who watched her.
The man said nothing. The woman thought: "If he prevents me now,
I shall—I must do it later. He can't change me. If he gives me in
charge he can't prove it. I've done nothing yet."
Yet she looked again, and this time did not turn away.
A strange magnetism which seemed to run through her, projected
from those eyes, was making even her finger-tips tingle as with a
new sensation, and one she had never known before. Her purpose
melted and dissolved in that flow of more than electric influence; it
changed as fire changes a material thing. It melted like snow before
the radiant energy of the sun.
Slowly she unwrapped the bundle. The paper, the cloth wrappings
she threw into the black and oily water, but the child she clasped to
her breast.
"My baby," she murmured, very quietly, but in tones that pierced the
tense atmosphere and reached Joseph's ear. "I bore you in shame,
and was about to kill you to save you from shame like mine; but I
will bear my cross and love you for the sake of Jesus. Amen."
She stole away, trembling. There was a great fear and wonder at her
heart, and the watcher saw no more.
Joseph smiled bitterly. His brain seemed some detached thing, a
theatre upon the stage of which wild thoughts were the conflicting
actors and his sub-conscious intelligence the spectator.
The simile of the shadow returned to him, and was it not all a
shadow—this dark, unhappy life of his? The words "radiant energy,"
the words "God" "conscious force" danced before him. The whole
sentient world was reeling—the blood that fed the grey matter of his
brain was poor and thin—this was the reason.
Yet, was it the reason, after all? What had happened to him in the
last few minutes? He felt as he had never in his whole life felt
before. There was a sense of extraordinary impotence. Something
had come into him; something had gone out of him.
No!—something had gone through him—that was the way to
describe it to himself....
Oh for food, rich nourishing food, quiet and fresh air—then all this
sickness would go....
Joseph left the docks, and was soon back in the teeming Commercial
Road. He walked, lost in thought, unconscious of all his
surroundings.
"Nah, then, Monkey Brand, 'oo y'r shovin'? I can see y'r gettin' a
thick ear, young feller-my-lad. Owns the bloomin' pyvement—"
A string of obscene oaths and the above words brought Joseph the
dreamer down to earth again—the world of the Commercial Road.
He had stumbled against a typical bullet-headed, wicked-eyed East
End rough.
The man stepped close up to Joseph, lifting an impudent and dirty
face, holding the right arm ready to strike the short, jabbing blow so
dear to the hooligan.
Then a strange thing happened.
Joseph, roused so suddenly and rudely from his bitter reverie,
became aware of what was toward. He was about to apologize to
the man when his words were checked in his mouth by the fellow's
filthy profanity. Joseph suddenly, instead of speaking, turned his full
face to him. The great, blazing eyes, their brilliancy accentuated a
hundred times by hunger and scorn, seemed to cleave their way
through the thick skull of the aggressor, to pierce the muddy and
besotted brain within, to strike fear into the small leathern heart.
The man lifted his arm and covered his face, just like a street child
who expects a blow; and then with a curious sound, half whimper,
half snarl, turned and made off in a moment.
It was an extraordinary instance of magnetic power inherent in this
starving scholar who roamed the streets in a sad dream.
On his own part, Joseph's action had been quite unconscious. He
had no thought of the force stored up in him as in an electric
accumulator. Some experiments in animal magnetism he had
certainly made, when he had taken a passing interest in the subject
at Cambridge. He had cured his "gyp" of a bad attack of neuralgia
once, or at least the man said he had, but that was as far as it had
gone.
He turned his steps towards the stifling attic he called "home." After
all, he was better there than in the streets. Besides, he was using up
what little strength remained to him in this aimless wandering.
He had eaten nothing that day, but at nine in the evening he had a
lesson to give. This would mean a shilling, and there were two more
owing from his pupil, so that even if Hampson, who lived in the next
garret, failed to get any money, both might eat ere they slept.
As he turned into the court and began to mount the stairs, Joseph
thought with an involuntary sigh of "hall" at Cambridge, the
groaning tables, the generous fare, the comely and gracious life of it
all.
And he had thrown it all away—for what? Just for the privilege of
speaking out his thoughts, thoughts which nobody particularly
wanted to hear.
With a sigh of exhaustion he sat down on the miserable little bed
under the rafters, and stared out of the dirty window over the roofs
of Whitechapel.
Had he been right, after all? Was it worth while to do as he had
done, to give up all for the truth that was in him. The old spirit of
revolt awoke. Yes, he had been right a thousand times! No man
must act or live a lie.
But supposing it was all true? Supposing there was a God after all.
Supposing that the Christ upon whom that woman had called so
glibly really was the Saviour of mankind? Then—The thought fell
upon his consciousness like a blow from a whip.
He leapt to his feet in something like fear.
"It's this physical exhaustion," he said to himself aloud, trying to find
an anodyne to thought in the sound of his own voice. "My brain is
starved for want of blood. No one can live as I have been living and
retain a sane judgment. It was because the hermits of old starved
themselves in the desert that they saw visions. Yet it is odd that I, of
all men, should weaken thus. I must go out into the streets again,
come what may. The mind feeds upon itself and conjures up wild
and foolish thoughts in a horrible little box like this."
With a heavy sigh he went slowly out of the room and down the
steep stairs. Never in all his life had he felt so lost and hopeless; so
alone and deserted.
Another man in his position would have called out upon God, either
with mad and puny revilings in that He had forsaken him, or with a
last piteous cry for help.
Joseph did not believe in God.
All his life he had lived without God. He had ignored the love of the
Father and the necessity of faith in His Son Jesus Christ. The temple
of his body was all empty of the Paraclete. Now he felt sure that
there was no God; never had been any God; never would be any
God.
He was at the darkest hour of all, and yet, with a strange nervous
force, he clenched one lean hand until the shrunken muscle sprang
up in coils upon the back of it, resolving that come what might he
would not give in. There was no God, only a blind giant,
Circumstance—well, he would fight that!
His mental attitude was a curious one, curiously illogical. Keen and
well-balanced as the scientific side of him was, the man—like all
those who openly profess disbelief—was unable to see what might
almost be called the grim humor of his attitude.
"I do not believe in God!" the atheist cries, and then immediately
afterwards shakes his fist at the Almighty and bids Him to do His
worst!
Man challenging God! There is no more grotesque and terrible thing
in human life than this.
But, as the world knows now, God had a special purpose in his
dealings with this man.
All unconscious of what was to befall him, of his high destiny to
come, Joseph walked aimlessly in Whitechapel, cursing in his heart
the God in whom he did not believe, and yet who had already
chosen him to be the centre and head of mighty issues.... A channel
as we may think now....
We may well believe that each single step that Joseph took was
known and regulated by unseen hands, voices which were unheard
by ear or brain, but which the unconscious and sleeping soul
nevertheless obeyed.
At last the Almighty spoke, and the first link in the chain of His
mysterious operations was forged.
Joseph was walking slowly past a great building which was in course
of erection or alteration. A network of scaffolding rose up into the
smoky, dun-colored sky.
The clipping of steel chisels upon stone, the echoing noise of falling
planks, the hoarse voices of the workmen as they called to each
other high up on their insecure perches, all rose above the deep
diapason note of the traffic in a welter of sharply-defined sound.
Joseph stepped upon the pavement beneath the busy works. He
was, he noticed, just opposite the office of the small East End
newspaper for which Hampson, the poor, half-starved, but cheery
little journalist did occasional jobs.
Hampson—good, kind, little Hampson! It was pleasant to think of
him, and as he did so Joseph's thoughts lost their bitterness for a
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookname.com

You might also like