Monitoring a home automation PC

Lesson learned today: always monitor a machine you intend to let run without interruptions for a long time. And that includes home automation hardware.

I have described elsewhere the steps to install Debian on an embedded PC. I’m still working on this project and intend to soon install the open-source Misterhouse software on it. But first I wanted to get a feel for how the machine’s resources (mainly disk and memory) evolve over time.

So I scouted for open-source monitoring software. There’s a great comparison on Wikipedia of different monitoring software (some proprietary), but my feeling was that it essentially boiled down to Cacti and Zabbix, both of which are variations on the PHP+MySQL+Agent theme. I knew Cacti from a previous project so I installed Zabbix on my Soekris box.

Good thing that I did. As you can see on the graph below, over a period of just 10 days the available disk space had shrunk by almost 2 Gb. Now this sort of thing happens almost always somewhere under /var, and indeed, it was caused by MySQL’s habit of logging every single data-altering statement in so-called bin files under /var/log/mysql.

Disk space evolution after two weeks

After commenting out the relevant lines in /etc/mysql/my.cnf the problem went away, but I had to restart the Zabbix server (without loss of data of course). And I’m sure the reader will notice the irony of MySQL being the cause of this decrease of disk space, when MySQL was installed together with Zabbix in order to monitor the system for such problems. Oh well.

ZigBee’s unkept promises

The Guardian carries an interesting story about yet another alternative to ZigBee: Ultra-low Power Bluetooth.

ZigBee has been touted since 2003 as a low-power, low-bandwidth wireless protocol ideally suited to home automation applications. But as the article makes clear, “we aren’t all drawing our curtains and turning on the lights with the touch of a button”. It is not clear why ZigBee hasn’t yet established itself in the market. A high barrier to entry might explain part of it. But according to the article, possibly the biggest obstacle to ZigBee adoption is its mesh topology, requiring all nodes to continuously listen to incoming data to pass on to the other nodes. Bluetooth, on the other hand, has a simpler star-shaped network but much more limited in range and number of devices.

From my earlier life working on a ZigBee-based home automation product I can testify how we often had power problems with our ZigBee devices. The alternative was to have them all dormant, periodically waking up and transmitting their (own) data. But then we are back to a star-shaped network, and we are unable to actively query a node for its current status.

There’s no easy way out of this dilemma. As the article has it, “you can’t do low power and mesh at the same time.”

X10 CM11A controller programming specs

The CM11A X10 controller (or its various incarnations, such as the CM12CH model for Switzerland), made by X10 Pro, is one of the most ubiquitous (and cheapest) X10 controllers available. If you want to write a program that will talk to this interface you will definitely need to know not only its communication protocol but also its serial line settings (baud rate, parity and so on).

Googling for this information wasn’t easy, so here is my humble contribution to the pagerank of the page that gives this invaluable information:

X10 CM11A controller programming specs

Debian installation on a Soekris embedded PC

Ubiquitous home automation will never become a reality unless cheap embedded PCs are available to be the “brains” of the home. Some time ago I came across a company called Soekris Engineering who make relatively cheap embedded PCs, like the one shown below.

net4801

This little guy packs a 20Gb CompactFlash harddisk, 128 Mb RAM, and a 266 MHz Intel processor. Of course I managed to hose mine’s operating system and had to reinstall it from scratch. Here are the steps I followed to install Debian from my laptop (running Ubuntu 7.10), connected to the Soekris with a null-modem cable.

Minicom setup

Install the minicom package on the host system, you’re going to need it to communicate with the Soekris box during the installation. Here is what my minicom configuration looks like:

Minicom default configuration

I also suggest you run the following before starting minicom:

export LANG=C

If you don’t you might run into strange error reports from minicom.

The Debian installer will by default talk to the serial line in 9600 bauds, so I suggest you make this the default in the Soekris comBIOS’s monitor program. After entering it, enter

set ConSpeed=9600

and reboot. Change the setting in minicom too.

DHCP setup

We’re going to start a Debian installer through PXE, so first we need a DHCP server configured to provide the right file. Install the dhcp3-server package on the host system. Configure it by appending something similar to /etc/dhcp3/dhcpd.conf:

subnet 192.168.0.0 netmask 255.255.255.0 {
option domain-name "visnet.ch";
option domain-name-servers 192.168.0.1;
option routers 192.168.0.1;
range 192.168.0.4 192.168.0.4;
option host-name "misterhouse";
next-server 192.168.0.69;
option root-path "/var/lib/tftpboot";
filename "/pxelinux.0";
}

Start the DHCP server.

TFTP setup

Install the tftpd-hpa package on the host system. Start the server with:

in.tftpd -l -s /var/lib/tftpboot/

Download Debian installer

Download the most recent Debian installer from the Debian download site. Untar it to /var/lib/tftpboot. Change the pxelinux.cfg symlink to point to the serial-9600 configuration:

drwxr-xr-x 3 root root 4096 2008-02-28 01:28 debian-installer
lrwxrwxrwx 1 root root 32 2008-05-09 21:45 pxelinux.0 -> debian-installer/i386/pxelinux.0
lrwxrwxrwx 1 root root 46 2008-05-09 22:00 pxelinux.cfg -> debian-installer/i386/pxelinux.cfg.serial-9600

Boot the Soekris

You’re now ready to boot the Soekris box. Enter the comBIOS’ monitor program and enter:
boot f0

And go through the installation process. Since the installer will download packages from mirror locations you should turn off the DHCP server on the host system, and let the Debian installer configure itself with your LAN’s DHCP server.

I called my system misterhouse@visnet.ch, since I intend to use it to run the open-source MisterHouse home automation program.

You will at some point be asked how you want to partition the 20 Gb disk. If you leave the default settings, you run the risk of not being able to boot because of an “Error 18” from GRUB. See here for an explanation. That’s why you should make the first partition a small (about 100 Mb) bootable partition mounted at /boot. The rest of the disk can be split between a 400 Mb swap space and all the rest.

Your setup should look something like this:

Debian installer partitions setup

When prompted, say yes to install GRUB on the master boot record.

You will also be asked what types of software to install. For a standalone, headless mini-server like this, I configured it like this:

Debian software types

Conclusion

That’s pretty much it. When you’re all done the installer will prompt you to reboot the system, which will then boot into Debian. Login with the username you provided during setup. I strongly recommend you install a SSH server or you won’t be able to login other than by the serial console:

aptitude install openssh-server

That should be it. Enjoy your new home automation central system.

Monitoring home electricity usage

If you can measure it you can control it, and that is also true of your energy consumption.

Two energy-monitoring devices have recently been brought to my attention that are not only easy to use, but also to install. The first one is the OWL, and consists of a wireless clip you put around your house’s main electricity cable. Data is then transmitted to a portable LCD device. I suppose it works by measuring the magnetic fields induced by the current.

The other one is the Wattson. It works along similar principles, but is maybe just a bit more stylish.

I welcome the introduction of such devices on the market. I’ve heard that when consumption meters were introduced in cars, their owners started paying attention to it and adjusted their driving accordingly. Some do it for genuine economic reasons, but others do it simply for the fun of it. These sort of toys are simply irresistible to us grown-up children.

Perhaps the only, small gripe I could have against the OWL or the Wattson is their lack of granularity. You measure the total energy consumption of the house, and cannot measure the consumption by appliance (fridge, oven, etc) or by kind (lighting, heating, etc). And I don’t suppose there’s any way to record historical data from them. But never mind, they’re cool nevertheless.

OptiControl project website

Recently I got this email from Dr. Dimitrios Gyalistras of ETH Zurich:

I would like to draw your attention to the newly launched website of the project Use of Weather and Occupancy Forecasts for Optimal Building Climate Control (OptiControl):

http://www.sysecol.ethz.ch/OptiControl/

OptiControl is a collaborative effort by the ETH Zurich, EMPA Dübendorf, MeteoSwiss and Siemens Building Technologies. The project is sponsored by “swisselectric research”, the ETH Domain’s “Competence Center Energy and Mobility” and Siemens Building Technologies.

I hope that the website will be of interest to you. Its contents will be updated regularly to reflect the project’s results and the newest literature in the field of predictive building climate control.

OSGi Community Event, Munich 26-27 June 2007

I have already mentioned elsewhere that the OSGi technology is likely to play an important part in the computerization of current and future buildings. It is a very attractive programming model for building management systems, especially with respect to its software lifecycle model (stopping, updating and restarting) that does not require a reboot of the whole system—nor indeed of your own application.

In a nutshell, OSGi is an extension to the Java programming language whereby a framework program (just called the “framework”) runs continuously, in which small applications packaged as “bundles” (which are nothing else but jarfiles with some extra description information in their manifest) are installed, registered, started, stopped, updated and uninstalled. Each bundle can register “services” in the framework, i.e. objects available for use to other bundles. In a carefully designed OSGi program, when a bundle is uninstalled all bundles forget everything about it, and in particular its classes are eventually unloaded—something that never ever happens in classic Java (or any other language that I know of). For this reason, OSGi has more than once been referred to as “ClassLoaders on steroids”.

This being my weblog on building automation, I report here what I found to be relevant for that field in the OSGi Community Event held in Munich, Germany, June 26-27 2007.

(Full disclaimer: my trip was financed by Adhoco AG, with whom I work, but I promise will be as unbiased as I can.)

OSGi Community Event

OSGi and home automation

There wasn’t actually that much of a specific focus on building automation per se—only Miguel García Longaró, from Telefónica Ivestigación y Desarrollo in Spain, and Marquart Franz from Siemens showed us products for the home automation. I found Miguel’s product to be particularly intriguing, as he claimed it could indifferently talk to devices on different kinds of underlying hardware (he listed EIB/KNX, Hometronic, Busing, Dinitel and X10). This is exactly what we offer with Adhoco’s product too.

One discussion that always comes up when discussing home automation with potential customers (and that is very often ignored by academicians) is the cost of the system. Miguel argues that for home automation to become a reality the residential gateways must cost less than about € 100.–. Over coffee I had an interesting discussion with Fred Verstraaten from Luminis, in the Netherlands. He argued that in the future, home automation should be a feature of the modem/router boxes you get for (almost) free when you sign up for high-speed internet. Those who want home automation pay higher monthly fees and get the bigger box, and buy the sensors/actuators separately.

I find it difficult to find faults with that line of reasoning. It’s in the interest of providers of home automation to guarantee a steady stream of revenue, something a subscription model can provide. And the cost barrier is, indeed, probably a major reason why home automation is not more widespread than it is today.

Home automation and industrial automation have a lot in common. Daniel Grossmann (from the Technical University of Munich) described an architecture whereby a central server manages all devices in a plant or factory, and provides OSGi bundles to client machines that need to access the data in these devices. Providing data from an arbitrary number and types of devices to client systems is a challenging problem, one that we face with home automation too. Daniel told us about the Electronic Device Description Language (EDDL), a formal language that describes the functions and data available from any device. His server reads this information from the devices in the plant and provides the adequate OSGi bundles.

I suppose this is an approach we could try with home automation as well, but what he is doing sounds awfully similar to the Device Access service specified in the official OSGi specs. When I asked him about this, he replied that device manufacturers prefer to distribute EDDLs for intellectual property reasons, which was (apparently) why he couldn’t use this service.

I must however confess being thoroughly confused by this service specification at the moment. I spent three hours on the train trying to understand it (once more) but gave up. I’ve started a thread about this on the Apache Felix (an open-source OSGi implementation) mailing-list.

I’ve often wondered whether it is better to have one central service responsible for dealing out references to the devices to client bundles, or if each device should be represented by a service. (This dilemma is faced by anyone architecting a distributed computing environment, such as network of automatic teller machines—do you have each ATM communicate with on object that represents the bank, or with thousands of smaller objects that each represent an account?) Richard Hall, author of the Apache Felix OSGi implementation, suggested that the latter model is better, as it allows client bundles to react to the “disapperance” of devices.

OSGi technical discussions

OSGi technical discussions

BJ Hargrave gave us a quick overview of the new features in OSGi 4.1. Only two important changes for the normal OSGi user:

1) Bundles can now be transiently started/stopped. This means, e.g., that if I transiently stop a bundle but forget to restart it, and the framework restarts for some reason, then the bundle will be restarted too. In release 4.0, if a bundle was stopped, this status was persistently saved no matter what, until you remembered to start the bundle again.

2) Lazy activation: it is now possible to specify that bundles are to be activated “for real” only when a class from them is loaded for the first time. They are still marked as Active before that (as I understood it). That can be nice if you have a large number of bundles that each take quite a long time to start but whose services are not necessarily immediately required.

Then we had also BJ Hargrave and Peter Kriens, resident OSGi evangelist, give a duet talk on OSGi best practices. This is what I noted:

Portable Code

You never know against what virtual machine your code will run, so always compile your code against the minimum suitable class libraries. OSGi defines Execution Environments (EE) for that.

Proper Imports

Never, ever import classes from libraries without a corresponding Import-Package statement in your manifest. The exception is java.* libraries. You should never assume the existence of library classes on your system—in particular libraries such as javax.*. (I could trade endless horror stories about my fights with XML parsers.)

By giving the proper Import-Package statement you guarantee that your application will die early (upon resolving, in fact) if those libraries are not available.

Minimize dependencies

A strong value that OSGi provides is the possibility to use different implementations of the same service. It usually makes no sense (and makes your application unnecessarily complex) to require a specific implementation of a given service.

Thus, prefer the use of Import-Package over Require-Bundle. The latter binds your application irrevocably to a particular bundle (and its provider) while the latter lets you chose which bundle, that implements the service you need, you want to install.

For related reasons, do not overspecify the bundle version you require but use version ranges.

Hide Implementation Details

Contrary to normal Java jarfiles, OSGi allows you to select which packages in the jarfile to make publicly available (to export, in OSGi parlance). It is generally recommended to put everything the client bundle needs (i.e. service interfaces) in the exported package and to hide all the implementation in their own, unexported packages.

I’ve seen different styles on how to implement this. You usually end up with two packages per service (or set of services). I have seen these naming conventions (with the interface package coming always first):

foo.bar.service.*
foo.bar.serviceImpl.*Impl

foo.bar.*
foo.bar.impl.*

foo.bar.service.*
foo.bar.*

foo.bar.osgi.*
foo.bar.*

It’s a matter of taste and readability. I am uncomfortable with having an interface and its implementing class with the same names (but in different packages), but on the other hand I dislike all these dangling Impls. I personally prefer the two latter examples.

An added advantage with having the “real” classes in the package with the shorter name is if your bundle is designed to be usable outside of the OSGi framework. You want people to import foo.bar.*, not import foo.bar.impl.*.

Avoid ClassLoader Hierarchy Dependencies

Dan Bandera, president of the OSGi Alliance, closed the OSGi event by saying that there must have been some really good technical talks because he did not understand any of it. I feel a bit the same with this point.

The bottom line was, don’t use Class.forName(). Don’t ask me why.

Avoid Start Ordering Dependencies

A canonical mistake I know I have been doing (now) is to fiddle with the framework’s start levels to make sure that my client bundle does not start before that HttpService bundle has been started.

It is much better, safer and cleaner to use the ServiceTracker or ServiceTrackerCustomizer classes. Your bundle should start as normal and wait until the HttpService service has been registered with the framework.

Handle Service Dynamism

This is very related to the point above: your bundles will be all the more robust if you remember that services can come and go. Always write your bundle as if there was a chance that the services it depends on could be (even temporarily) unregistered. Again, the ServiceTracker or ServiceTrackerCustomizer make this job easy.

WhiteBoard Pattern

Suppose you register an object as a listener with, say, LogReaderService.addLogListener(). Now the LogReaderService holds a reference to your object and will never, ever release it unless you call removeLogListener(). But suppose your bundle gets stopped, uninstalled or updated before?

This is an example where the classic Observer design pattern encounters problems with OSGi. You cannot any longer simply pass objects as event listeners if there’s any chance that these objects parent bundle can go away, with no possibility to inform the observed object.

The somewhat surprising idea is instead to have each listener register itself as a service. Then the observed object can query the service registry for all registered listeners and notify them of the event.

There a good whitepaper on this approach here.

Extender Model

Suppose you have a desktop application with a help system. You’d like to give client bundles the possibility to provide content to this help system.

One possibility is to have each client bundle register their content themselves with the help system. The problem is, again, what happens if the bundles goes away and does not remove the content?

The proposed solution is to have the help system (or any other content publisher) specify the format and location of the data it expects from each bundle—and then goes and fetches the data himself from the active bundles. For instance, it could specify that all help content should follow such-and-such XML format and be given in a help.xml file under META-INF. Then any client bundle who wants to publish help information includes that data in this help.xml file, which is retrieved by the content publisher.

Avoid OSGi Framework API coupling

This basically says that you should always keep the number of classes that import things from org.osgi.* to a minimum.

Personally I always try to design a bundle as if it would be used outside of OSGi. Most, if not all, of the OSGi calls can be restricted to a small number of classes (including the bundle activator). This will also make your application much easier to test and debug—you won’t necessarily have a OSGi framework handy when running your unit tests.

Return Quickly from Framework Callbacks

Although the specs are often silent on this point, most framework callbacks are synchronous. For instance, the BundleActivator.start() methods are usually called one after the other. But this means that if your bundle’s startup time is significantly long (say, more than one second) then the total startup time of your application can become unacceptable. Again, this depends on your kind of application.

But try to keep those startup times short. Less than one second is good. Use lazy activation if you can, now that it is available. Have all framework callbacks return in a timely manner. As a last resort, consider spinning a new thread off so the callback can return while you continue the “real” activation of your bundle.

Thread Safety

Like many other of these best practices, this one holds for any Java application and is not restricted to OSGi. This is a complex subject, with some members of the meeting nominating Brian Goetz et al’s book Java Concurrency in Practice as a required reading for any serious Java developer.

I am by no means a concurrency expert, but a common cause of deadlocks is when you make foreign method calls inside a synchronized block. Do not, ever, do this. You have no idea what that method you are calling might be doing—in particular, it might well try to acquire your own lock, resulting in a deadlock and a frozen application.

OSGi evangelist in action

Miscellaneous

When he wrote the original open-source Oscar implementation of the OSGi specs, Richard Hall introduced the idea of a bundle repository: a centralized place from where OSGi bundles can be downloaded, and whose contents are described in a XML format.

He gave a talk on the history of what is today called the OSGi Bundle Repository (OBR), the logical continuation of his original idea. This is the official OSGi bundle repository to which vendors are encouraged to contribute, but the OBR also allows one to setup a private bundle repository. Felix comes with a OBR service to communicate with such repositories.

In my line of work I have found the OBR idea very useful, and a great tool for setting up a remote management system. Such a repository can hold different versions of the same bundle, making lifecycle management easy. What makes the developer’s life even easier is the availability of the Bindex tool from Peter Kriens to generate the repository’s description XML file.

Stuart McCulloch talked about other tools for bundle developers. It was from him that I heard for the first time about the Bnd tool to help create OSGi bundles. Like probably many others, I’m still relying on good old Ant scripts to do that, so any tool that might make it easier is welcome indeed.

Remote management was often mentioned during the event. Kai Hackbarth, from ProSyst AG, gave a talk on the challenge of managing the lifecycles of potentially millions of OSGi devices in the field, not all of which can be assumed to be connected to the internet at all times. He presented the mPRM software product that his company makes, a product that helps automate this daunting task.

OSGi discussions

Overall impression

This was the second OSGi event I attend, the first one having been the 2005 OSGi World Congress in Paris. I personally found the Munich event somewhat less informative for my own interests, possibly due to the high percentage of business presentations. The technical presentations were, however, excellent and I managed to make more contacts than in Paris. I would have loved to see more “hands-on” presentations, showing examples of the use people make of OSGi but more into the technical aspects. But I guess that’s just not possible in a two-day plenary meeting, and the organizers did a fantastic job for this community event.

Raclette machine control with X10

This Saturday I turned on our new raclette machine at our flat from my computer.

There is a fairly well-established home automation standard in the U.S. called X10, invented in 1975. It allows for the simple control of appliances, lights and other home equipment, using a communication protocol over the power lines.

It has however never been much popular here in Europe, and for a time I could never find a distributor of X10 equipment compatible with our swiss eletrical outlets. There is one however; on their website we europeans can finally find all the necessary equipment to carry out most of the hacks described in the book “Smart Home Hacks”.

I had our laboratory order some starter kits and elementary equipment in order to test things out. I will regularly post to this weblog updates on my tests and projects with this equipment; in the meantime, I would like to share my experience in setting up my computer to communicate with X10 from a Java program.

First I downloaded the software written by the Java X10 Project. This software includes useful examples to control simple appliances or lamps. However, it also needs an implementation of Sun’s Comm API, necessary for communicating over the serial interface.

I have had some very bad experiences with commercial implementations of this API so this time I tried out the open source RXTX implementation. You need to download the source and follow the INSTALL file scrupulously for this to work, including the contrib/ChangePackage.sh script. The compilation will look like it’s stuck in an endless loop but in fact it isn’t. Just be patient.

Once this was done, I could run the appliance example of the Java X10 project, which displayed a window with a single On/Off button. After making sure that my raclette machine was connected to an X10 applicance module with the right house and unit addresses, I clicked “On”, and heard the actuator switch on in the kitchen.

PS. If you are going to try this at home, make sure all the protective cellophane has been removed from your raclette machine first. I could switch the machine off in time to open the windows and ventilate before my wife could notice the heavy smoke. I guess no computer will ever completely prevent human errors. 😛