Mar 11, 2012

Is TDD one of the solutions for difficulty of concurrent development of software and hardware?

In my 5 year experience of embedded software engineer, I became to think concurrent development of software and hardware is the biggest risk of embedded systems. I thinks TDD is one of the solutions for the problem. So I held a book club of "Test Driven Development for Embedded C (Pragmatic Programmers)" in Tokyo. Here is my thought on how we fight with difficulty of  concurrent development of software and hardware.


Writing code for uncompleted hardware is so hard : (

General process of embedded software development is as follows:
  1. Developing software on own computer
  2. Debugging on an evaluation board
  3. Testing on a target hardware
At the first step, we don't have the target hardware and have to write code for imaginary hardware that we have never seen. After we got the evaluation board, which is the second step, we try to debug on it to find bugs.

Most of engineers that I have met try to debugging on an evaluation board as quickly as possible, so they tend not to care about testability for unit test. As a result, we get high coupling code.

At the time, we have to advance the development with several risks as follows:
  • Own computer, evaluation board and target hardware have a little bit different library and compiler.
  • The evaluation board is bad in quality at the beginning of the development.
  • There are many mistakes in logic of code
  • Software engineer has to resolve underlying discrepancy in specification at the end of development.
  • etc.
Problems occur someday. They make debugging time longer and distinguishing cause of bugs more difficult.

If we do agile software development for embedded software system, this will be a bottleneck.


Dual-Target Testing

For this problem, the author of "Test Driven Development for Embedded C (Pragmatic Programmers)" recommend hardware-independent software design and unit test on both of own computer and evaluation board from the beginning. This is called "Dual-Target Testing". If we do it from the beginning, we can eliminate bugs and make test easier.


What do we need for Dual-Target Tesing

At first, we need software design techniques to make software more testable. That is discussed in the books like "Test Driven Development: By Example" written by Kent-Beck or "Working Effectively with Legacy Code" written by Michael Feathers.

Second, we need cooperation with hardware engineers for low layer software development. For example, in the book of "Test-Driven Development for Embedded C ", there is a scene that software engineer and hardware engineer are discussing about design of interface between software and hardware so that software engineer can decide design of Test Double.


What "Test-Driven Development for Embedded C" is doing for this?

There are some code examples in my github. There is product code and test code for LED driver.

Key point of this example is a dependency injection at a constructor. Passing writing port address to constructor makes software independent with hardware. We can do unit test on both of own computer and the evaluation board.

This driver has writing port only. State of LED driver is stored at variable ledsImage once, then write to the port. This was an issue that software engineer and hardware engineer discussed in the book.

You might think that this example is quite simple and there are more difficult examples in real world. I think basic idea is the same as this example, which is interface design between software and hardware and low coupling software design against hardware and other software modules.

I will held the third monthly meeting of "Test Driven Development for Embedded C" book club in Tokyo and see this problem deeply : )

Feb 6, 2012

The book club of "Test Driven Development for Embedded C" started in Tokyo, Japan


The book club started today : )

Core members of the book club met at "TDD Boot Camp Tokyo for C++" in 2011. This was the event that embedded or game engineers got together and had a TDD practice.

At that time, I wrote my position paper like this: "I want to learn TDD for embedded software, so I want to hold a book club of Test Driven Development for Embedded C. Why don't you join? " To my delight, two engineers said to me that they would join. After I called for participants of this book club on Twitter, 10 engineers joined! That was how we started.

What is motivation of participants?

Participants are embedded software engineers of MFP, medical devices, communication devices, home electronics and etc. We have common point. We have legacy code, code without tests, in our projects and have a hard time of debugging. This is unpredictable activity.

To reduce time of debugging, to discovery bugs rapidly, we are paying attention to TDD.

What we read today

Today we read the first three chapters.

The first chapter "Test Driven Development" introduces what is TDD, purpose of TDD and benefits of TDD.

TDD is one of design techniques, so I can say that I do TDD to improve software design. But the biggest purpose of TDD is to prevent from bugs by getting quick feedback of test results and find mistake rapidly.

The second chapter "Test Driving Tools and Conventions" introduces Unity for C and CppUTest for C/C++ as testing frameworks that were introduced in this book.

CppUTest has a function to add tests into test suite automatically. This is very good for TDD. And it was developed with old function of C++ so that old compiles can compile it.

Unity doesn't have a function to add tests automatically but there is ruby script to do it. It is very convenient.

The third chapter "Starting a C Module " introduces the steps of TDD. We try practical example, LED driver. In this chapter, we can learn embedded software version of Dependency Injection. That is to put physical address of LED driver at runtime. With this way, we can separate software from hardware and we can get benefit to test without hardware.

What we didn't understand

We didn't understand following two points.

The first point. Can we design like this LED Driver example in real project? This example is OK because it is so simple. But in real project, dependency of hardware is so complicated. Changing physical address affects other hardware in some way. So we don't design like this.

Maybe, we can test only where we want to test without representing complicated hardware interaction. (I don't know how to do it)

Or, we don't test bottom of embedded software but focus on upper layer, which is hardware abstraction layer. That is easier to test than bottom layer. In this way, we can't test everything but we can reduce debugging time.

The second point is how we test mass of legacy code. If we need too much time before starting TDD, we lose motivation. To do TDD for real project, we need way to reduce initial cost and introduce TDD incrementally. The 13th chapter may introduce how to fight against legacy code. In near future, we can learn how to do it : )

How I felt after first time

We found that we have so many unknowns this time but we felt joyful that we got together at this book club. I want to say thank you to organizer of "TDD Boot Camp Tokyo for C++" and Mr. James W. Grenning. the author of Test Driven Development for Embedded C.

My job is to make the place that participants can learn a lot and enjoy : )

Sep 21, 2011

How to compile googletest with gcc and CMake on Mac OS X SnowLeopard

I often found the way with Visual Studio C++ or XCode on web but I don't use them on my laptop. So I researched the way without IDE.

My settings
  • Mac OS X 10.6.8(Snow Leopard)
  •  gcc 4.5.4
  • cmake 2.8.5
According to googletest's README, you need more than 2.6.4 of cmake but the version of gcc is not clear.

Process
  1. Get source code of google test from svn repository
  2. Build googletest with cmake
  3. Create source file that has main function
  4. Create test code
  5. Build test code with g++
  6. Run the test
(1) Get source code of google test from svn repository

Place the source where you want.
svn checkout http://googletest.googlecode.com/svn/trunk/ gtest-svn

(2) Build googletest with cmake
Make a directory that cmake runs, which is good for anywhere.  {GTEST_DIR} is where theres is googletest. It is success when you get libgtest.a and libgtest_main.a after build.

mkdir mybuild
cd mybuild
cmake ${GTEST_DIR}
make

(3) Create source file that has main function

Create source file that has main function. You can find sample as below link.

You have to call below functions in main function.
  • testing::InitGoogleTest(&argc, argv); 
  • RUN_ALL_TESTS();

#include <iostream>
#include "gtest/gtest.h"

GTEST_API_ int main(int argc, char **argv) {
  std::cout << "Running main() from testmain.cc\n";

  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
(4) Craeate test code
#include "gtest/gtest.h"

TEST(firstTest, abs)
{
  EXPECT_EQ(1, abs( -1 ));
  EXPECT_EQ(1, abs( 1 ));
}

(5) Build test code with g++
You have to add the directory where there is googletest's header file into include path. You also have to build test code with static library of google test that you made at (2).

As below, testmain.cc is a file that has main function and mytest.cc is a file that has test code.


g++ -I{GTEST_DIR}/include testmain.cc mytest.cc libgtest.a libgtest_main.a -o mytes

(6) Run the test
Run the test. It is success if you see the test result as below.




Sep 20, 2011

auto_ptr and shared_ptr for resource management


Resource management is common troublesome issue for C/C++ programmer. If you don't free a resource that you acquire, you will run out of resource some day.

Scott Meyers, the author of Effective C++, recommended RAII(Resource Acquisition Is Initialization) for resource management. There are several ways to do it but simple way is to use auto_ptr and shared_ptr if your concern is about memory.

Give you a couple of example.

In this example, an error occurs before you delete an object that you acquirer, so resource leak happens. So you have to care about somebody except you because he can write a code that resource leak happens.

Investment* createInvestment() {
  return new Investment;
}

// an example of memory leak                                                                              
void f1(){
  std::cout << "f1" << std::endl;
  try {
    Investment *pInv = createInvestment();

    //If some one write code that can throws error,                                                       
    //destructor of Investment may not be called.                                                         
    throw 1;

    delete pInv;
  } catch(...) {
    std::cout << "catch" << std::endl;
  }
}

In this example, I used auto_ptr for resource management. Now you don't need to care about resource. When the control flow leaves the scope, auto_ptr frees a pointer.

//an example of auto_ptr                                                                                  
void f2(){
  std::cout << "f2" << std::endl;

  try {
    //If you pass a pointer to auto_ptr,                                                                  
    //auto_ptr frees it when the control flow leaves the scope.                                           
    std::auto_ptr pInv(createInvestment());
    throw 1;
  } catch (...) {
    std::cout << "catch" << std::endl;
  }
}

auto_ptr has several limitation. For example several auto_ptr cannot contain the same pointer. So you cannot put auto_ptr into STL container because STL container assume that every object can copy.

void f3(){
  std::cout << "f3" << std::endl;
  //several auto_ptr cannot contain the same pointer.                                                     
  //If you copy auto_ptr, then the source becomes null pointer and                                        
  //the destination can contain the pointer.                                                              
  Investment* pInv1 = createInvestment();
  std::auto_ptr pInv2(pInv1);
  std::auto_ptr pInv3(pInv2);
}

If you need to contain the same pointer with several auto_ptr, you should use shared_ptr in Boost Libraries. But shared_ptr has limitation. You cannot use it for an array.

void f4(){
  //several shared_ptr objects can have the same pointer.                                                 
  boost::shared_ptr pInv1(createInvestment());
  boost::shared_ptr pInv2(pInv1);

  //If every shared_ptr objects are freed, then the pointer                                               
  //that they have also freed.                                                                            
}


Here is a sample code for this entry.
https://github.com/yohei1126/effectivecpp/blob/master/chap3/term13/Investment.cpp

There are other ways for resource management. I will write it some day :)

Sep 17, 2011

One liner is a good way to do some smaller jobs in your life


Perl one liner is a good way to do some smaller jobs in daily life like renaming a file name or showing a file list.

You may think that you can do it by writing a script or a program. But one of the advantages of one liner is that you can combine it with other command like UNIX pipe and filter.

Here is an example of Perl one liner. You can pick up source files and header files for C/C++ language. It is not so difficult.

perl -MFile::Find -e 'find(sub {print "$File::Find::name\n" if $File::Find::name =~ /\.(c|cpp|h)$/ }, ".")'

You may say that you want to write other language. It is OK. You can use any LL but you may have some limitation in older OS. For example, I am using Open VMS, which is OS by HP, and I can use only Perl in LL. It is good to learn basic of other language for you.

I hope you will write some one liner in your work :)

Sep 5, 2011

Best Cow Line (POJ 3617)

You actually can solve the problem No. 3617 in POJ, Peking University Judge Online, with the greedy algorithm.

The author of "Programming contest challenge book" says that the greedy algorithm is effective for a problem that deal with dictionally order.

Here is more simple description of POJ 3617.

- - - - -


Description:
You have a string S that length is N and make a string T that length is N. At the beginning, length of S is zero. You can do either operation from below:

 - delete the first character of S and add it into the end of T
 - delete the last character of S and add it into the end of T

Make T as small as in dictionary order.

Constraint:
1 <= N <= 2000
string s can contain small alphabet.

Sample Input:
N = 6
S = "ABCDBCB"

Sample Output:
ABCBCD

My Solution:
https://github.com/yohei1126/pccb/blob/master/beginner/search/GreedyAlgorithm/BestCowLine/BestCowLine.cpp

Interval Scheduling Problem or a.k.a Earliest Deadline First Scheduling

Here is another example of the greedy algorithm, "Interval Scheduling Problem". You can find detailed explanation on Wikipedia. 

If I explain how this algorithm can work in an instinctive way, I can say like this:
  • The earlier a job ends, the more jobs you can choose.
This is not a proof. If you want to know how to proof, please see  "Earliest deadline first scheduling" on Wikipedia. Earliest deadline first scheduling is is a dynamic scheduling algorithm used in real-time operating systems.

-----

Problem:
You have 'N' jobs. Each job starts at time 'si' and ends at time 'ti'. You have to choose join or not for each job. If you join, you must jon from the beginning to the end of the job. You cannot join more than two jobs at one time. An overlapping of start time and end time is not permitted. You want to join as much as possible. Hou many jobs can you join?

Constraint:
1 <= N <= 100000
1 <= si < ti <= 10^9

Sample input:
N = 5
s = {1, 2, 4, 6, 8}
t = {3, 5, 7, 9, 10}

Sample output:
3

My Solution: