Dienstag, 20. Dezember 2011

Shutdown a second harddisk in Mac OS after suspend

I recenctly replaced the main harddisk in my MBP wit an SDD (a Crucial M4, 256GB - runs perfect). As i wanted to have my photo library with me and also wanted more space media data and virtual machines in that device, i also replace the optical multidrive with a magnetic 1 TB disk mounted in a special adapter. All worked very nice, execep one thing: whenever the macbook woke up after a suspend, it would spin up the magnetic disk and keep it on all the time. Most of the time i dont need the additional HDD, so this was annoying. Tuning the energy options did not help, it was constantly running, wasting battery capacity and being noisy rotating. As i got tired of ejecting the disk manually in the diskutility, i eventually managed to put the disk to shutdown immediatly after the system wakes up. First ist installed sleepwatcher http://www.bernhard-baehr.de/ - you can download it as a .tgz there and install it as described in the readme file. After all components were placed at their locations in the filesystme (you need to use "sudo" for most copy operations) i installed two small shellskripts in my home directory: ".sleep" and ".wakeup". The .sleep file is completely empty, the .wakeup contains basically one statement:
#!/bin/sh  
/usr/sbin/diskutil eject /dev/disk1
Problem solved!

Mittwoch, 14. Dezember 2011

Energy monitor redesign

Yesterday i did a complete redesign of my energy monitor system. It is based on an Atmega32 running on a Pollin RF-Evaluation Board connected to three current clamps for measuring the current in the three phases of my house wiring. The current clamps are place just before the RCD in our home.


The software on the Mega32 Energy-Node was based on the ethersex-framework. It worked pretty well, until i added more wireless node to the 433 MHz network. After a Jeenode running ethersex went online, i experienced frequent hangups of the energy node.
So i had the choice between either fixing the hangups or port the Arduino-compatible JeeLib software to my controllers. As the ethersex framework  has grown to a really big project i found it hard to surf through all the source to check whats going on in the software. So i decided to go for the arduino stuff. This code basically consists of small hardware drivers and the main application loop. Clean, simple, easy to understand, and until now - stable.
Especially the JeeLib-Code is designed for low-power devices, and it will be easier to build a battery based application with this codebase.
So first i set up an Eclipse environment for development. I ported the arduino stuff to work inside a C++ Eclipse project and integrated support for automatic programming with avrdude. The arduino Mac application is fine for an easy start, but i like my used eclipse environment for development. This was all pretty straight forward due to the work auf the AVR-Eclipse-Plugin, the Crosspack AVR Crosscompiling-Toolchain for Mac OS X and theAVR-Netino project.

After the Basestation and Energymonitor-Node were able to run basic demo "sketches" (Arduino slang for 'main application loop'), is continued added more functionality. More on this later.

Protocol thoughts

As explained in my previous post, i will look for a way to push information into my monitoring system. I have not yet decided which protocol and format to use.

There are at least two protocol layers you have to care about: The application layer and the transport layer. While the application layer carries the payload data like sensor readings or actor commands, the transportation layers job is to ensure a correct transmission of that data.

For the application layer,  i thought about using something like XML or JSON. While these "full-grown" standard protocols offer the possibility to use the hole bunch of development tools and libraries, they add a lot of processing and transmission overhead. When thinking of wireless sensor networks, you always have to keep in mind the low bandwith of their connection and their sometimes very limited energy ressources. It would be cool to have a sensor node running of a mini solar panel for example. For this reason, i currently prefer a more simple binary protocol that just carries the data needed. 

Same thoughts apply to the transportation layer. First thing that came to my mind was "hey, lets just use TCP/IP". Cool things about IP and TCP are: it's
  • stable
  • provides a secure transportation layer
  • is easy to program with all programming languages (standard sockets)
  • easy to add a encryption layer and firewalling
  • and you got big pile of standard debug, development and monitor solutions for it
so at first i thought it would be the perfect solution for my wireless nodes. But there are a number of disadvantages when using TCP/IP.

First: Overhead. Both in transport data volume and processing efford. There is a lot of information involved that is needed to keep the internet running - e.g. routable addresses

Second disadvantage is: TCP tries to ensure that all data send to the remote receiver gets submitted, using various tricks like ACKs, sequence numbers, the three-way-handshake, retransmissions, growing timeouts and congestion control. When you are transmitting data from a sensor network this does not always make sense. While some events should be transmitted with high security (like "the mailbox was filled" or "open the garage door") some other just get outdated too fast. When you transmit a temperature reading every 5 seconds or so, it just makes no sense to try to resubmit a lost transmission over and over again, as there might be a new sensor reading while the last one still is not transmitted. You better just try to submit it for a few times, and if that does not work, you just wait for the next reading and try again. Its sometime no problem to loose readings, its not critical.

Montag, 12. Dezember 2011

Polling vs. Pushing

My current setup used a regular polling of the sensors to collect and update the environmental information. This was the easiest way to do it during development of the prototypes. The Ethersex-Framework provided all the functions necessary to run a webserver that could be reached via the 433 MHz transceiver (which is a pretty cool feature, BTW!). But of course HTTP adds a lot(!) of overhead to the payload data.

I now changing that polling method to something more efficient. Reading out HTTP is fine for fast progress during development, as you can use all the standard commandline tools like curl, cut, tail etc.. but is wont scale.

In general polling itself does not scale. When you think of running a battery operated sensor node, its just impossible to have the webserver reachable wireless all the time. What you need is an event-driven communication, where the senor wakes up upon an event or regularly, transmits its information and then goes back to low-power-suspend until next time. Only this way of operation will ensure an acceptable battery lifetime.

Sonntag, 11. Dezember 2011

433 MHz Accesspoint

This is what my 433 MHz accesspoint (well actually its a router) looks like:

It consists of an AVR NetIO Board i bought from Pollin.de plus the RFM12 433 MHz transceiver. Its firmware is based on Ethersex. All communication is currently done using TCP/IP. The sensor boards run a minmal webserver, from where the sensor information gets polled regularly. After some ugly bugs where fixed recently and after i added some capictors to stabilize the ENJ28J60 ethernet IC, it runs stable since a week or so.

Home automation infrastructure

As my experiments with the energy meter are running fine and its all a lot of fun, im going to try to add some more sensors to my home.

This is what my current architecture looks like (in my mind, at least):



I already got a NAS (a Synology DS211, which is great btw) up and running at home and there is also the embedded linux controller. It is a bit redundant to have two devices running parallel, but the embedded linux box is a really low power one, running 24/7 consuming only 2-3 Watt while the NAS takes 20W and currently shuts down at night to save energy.

I have not yet finally decided whether the home automation stuff shall run on the one or the other device. I just started with the embedded board, as it runs a standard (ARM) debian distribution and i just needed some shell skripts and dont have a SQL integration yet. Maybe i'll also set up a toolchain for the NAS system to deploy the automation software there. But before doing that, i need some more sensors.

I think i makes sense to first add some sensors and monitoring software to see if the systems runs stable. After all, its a pretty complex setup involving many components. And any failing component would be a show stopper.

As the next steps i plan to monitor the temperatures, lightlevel and motion in all rooms. I also want to add a humidity sensor to the bathroom, maybe also the other rooms.

Therefore i just ordered some JeeNodes from Jeelabs. I still have some RFM12 units and sensors in my box, so i plan to start building more sensors based on them.

Mittwoch, 7. Dezember 2011

Stand der Technik

Vor ziemlich genau zehn Jahren habe ich das erste Mal eine VDR Installation gesehen. An der FH an der ich mich eingeschrieben hatte, fand im Sommer vor meinem ersten Semester ein "Computercamp" statt. Dort hatte ein späterer Kommilitone einen Opel Corsa voller Hardware mitgebracht. Unter anderem war eine Satellitenschüssel dabei, die wir mit viel Panzertape an mehrere Stühle montierten und durch das Fenster gen Astra-Satellit richteten. Über eine Satelliten-Tuner-Karte landete der empfangene Datenstrom in einem Linux-PC auf dem diese VDR Software lief. Es dauerte nicht lange, da hatten wir einen Stream aufgesetzt, und man konnte per Multicast von überall im Netz aus fernsehen (was die Switches ziemlich ins schwitzen brachte..). Das fand ich so faszinierend, dass ich ein paar Wochen später ebenfalls einen VDR-Rechner zusammengebaut habe.

Seitdem habe ich stets in dem Themenbereich herumexperimentiert und geschaut, was so alles möglich ist. Und der aktuelle Zwischenstand begeistert mich ziemlich. Das hat viel damit zu tun, was der Obstladen aus Cupertino und Google in letzter Zeit so entwickelt hat, aber ich denke auch, dass es einfach diese Zeit gebraucht hat die Technologie soweit zu bringen, dass sie täglich gut und einfach nutzbar ist.

Ein paar Beispiele:

  • Eine meiner Lieblingsanwendung: Airplay. Ich habe mir kürzlich einen AV Receiver mit Airplay zugelegt (einen Pioneer VSX-921K). Nicht nur, dass man das Gerät komplett per iOS oder Android App vom iPad und Smartphone aus fernbedienen kann, nein, das absolute Killerfeature für mich ist, dass der Receiver sich automatisch anschaltet und den passenden "Eingang" auswählt, wenn ich ihn vom Mac/iPad aus als Ausgabegerät auswähle. Es macht Klack, die Kiste bootet, und ein paar Sekunden später kommt die Musik aus den Hifi-Boxen und die Lautstärke lässt sich über den Schieberegler in iTunes/Airfoil/Simfy einstellen. Fantastisch. Früher habe ich versucht so etwas mit den Audio-Deamons unter Linux und Extra-Software wie NMM hinzubekommen. Das war kompliziert - oft stundenlange Tüftelei bis es lief - und meist unzuverlässig. Es hat natürlich dennoch Spaß gemacht, damit zu spielen, weil es zu der Zeit noch nicht selbstverständlich war, aber es gut, eine stabile, einfache Lösung für den täglichen Gebrauch zu haben.
  • Ebenfalls sehr cool finde ich Möglichkeit mit dem iPad/iPhone entweder Inhalte direkt auf dem großen LCD-TV ausgeben zu können, oder dieser Geräte per Remote-App als Fernbedienung für die Steuerung der Wiedergabe nutzen zu können. Ich war früher schon begeistert, als ich gelernt habe, wie man X11 Programme über das Netzwerk auf einem anderen Rechner darstellen konnte. Das ist heute geradezu trivial möglich - und noch viel mehr.
  • Man mag von iTunes halten was man will - und viele Dinge sind sicherlich auch suboptimal - aber  das Konzept "digital Hub" geht auf, wenn man sich darauf einlässt. Hat man erstmal alle Musik/Filme/Serien/Podcasts im iTunes Repository, dann sorgt die Software zuverlässig dafür, dass die Inhalten auf allen Geräten synchronisiert zur Verfügung stehen. Das schließt sogar die Playcounts und die aktuelle Wiedergabeposition ein. Beispiel: Ich höre auf Heimweg von der Arbeit auf dem Rad einen Podcast. Der Inhalt ist interessant, und ich möchte ihn gerne zuhause weiterhören. Dann wird der iPod fix an den MAC gestöpselt, und die Wiedergabe per Airplay auf dem AV-Receiver gestartet. Schon läuft der Inhalt nahtlos weiter. Will man abends im Bett noch ein Folge der Lieblings-Sitcom schauen, ist das über die Privatfreigabe von iTunes ebenfalls kein Problem. Der Inhalt wird einfach übers WLAN rübergestreamt.
  • Die "Photostream" Features von iOS und Android (über die Plus-App) gefallen mir ebenfalls sehr gut. Man macht mit dem Smartphone ein Photo, und Sekunden später ist es auf allen möglichen Geräten verfügbar, z.B. um es in ein Online-Posting einzubauen. Kein nerviges USB-Kabel-synchen mehr. Klar, mit Dropbox geht das prinzipiell schon länger, aber erforderte doch noch immer etwas Handarbeit.
  • Backups: Nie war es für mich so einfach, ein zuverlässiges,aktuelles Backup zu erstellen, wie derzeit mit der MAC Timemachine, die auf mein Synology NAS sichert. Die Einrichtung ist in ein paar Minuten passiert, anschließend sichert ein Hintergrunddienst meine geänderten Daten. Geht die Platte kaputt, kann man das System einfach wieder von NAS installieren. Das habe ich bisher schon dreimal ausprobiert (Anlässlich von Festplattentauschs oder Systemupgrades) und es hat jedesmal problemlos funktioniert. Klar ging das auch vorher schon immer mittels RSync und Co, aber die Einfachheit und Klarheit der Lösung ist bestechend.
  • Musik-Streaming-Dienste: Mit Napster und Simfy sind in Deutschland ja mittlerweile zwei Dienste vertreten, die meine Wünsche als Musikkonsument meist erfüllen. Aktuell bin ich zahlender Simfy-Kunde, nachdem ich Napster wegen Mangelndem Support für mobile - und nicht-Windows Geräte gekündigt habe. Für ca. 10 € im Monat erhält man Zugriff auf Server voller Musik. Die Musik kann man streamen oder aber lokal herunterladen und auf dem Rechner/Smartphone/Tablet spielen. Seit ich Zugriff auf das wohlsortierte und aktuelle Musik-Verzeichnis habe, spiele ich nur noch wenig Musik aus meiner MP3-Sammlung. Einziger Wermutstropfen für mich ist, dass ich die Alben nicht auf meinen iPod übertragen kann. 
  • Akkulaufzeiten: Sowohl Laptop als auch Table haben Laufzeiten von ca. 10 Stunden und man muss sich nicht mehr ständig Sorgen über die Restlaufzeit und die nächste erreichbare Steckdose machen. Das Android-Smartphone will allerdings jeden Tag an die Ladung, das dürfte gerne noch länger halten.
  • Mobile und heimische Netzverfügbarkeit: Mit dem Smartphone bin ich für 10€ monatlich dauerhaft mobil online. Für 25€ im Monat bekomme ich eine 32Down/1Up MBit Flatrate. Ich errinere mich noch gut genug an Modem und ISDN-Zeiten mit horrenden Telefonrechnungen und der steten Suche nach dem günstigsten Call-by-call Provider, um das zu schätzen zu wissen.
  • Günstige embedded Geräte. Auch wenn ich den Arduino-Board manchmal etwas skeptisch gegenüber stehe: Was sich die die ganze *duino-Bewegung in letzter Zeit im Bereich der coolen Basteleien mit embedded Geräte getan hat ist wirklich beachtlich. Es ist mittlerweile sehr leicht, einen Einstieg in die Thematik zu finden und das Web ist voll mit Informationen und Anregungen zu Projekten.

Alles in allem finde ich sind also grad ein paar sehr schöne Entwicklungen im Gange, die die Technik anwenderfreundlicher und angenehmer zu benutzen machen.

Donnerstag, 1. Dezember 2011

Integer overflows

Yesterday my newly installed energy monitoring system broke. While the dryer was running, the power usage suddenly jumped from a realistic 3500 Watts to 45000 Watt or so. What happened was, that an overflow of one or more variables must have occured somewhere in the firmware. I use unsigned int16's (uint16_t) for holding the 10 Bit sample result, which then get squared and summed up.

As i capture 200 samples for my True-RMS current measurement, the maximum value for each sum should be 200*1023*1023=209305800 which is twenty times below 2^32 - 1 (4294967295) which is the limit for an unsinged 32bit integer value.

Anyhow, the energy meter went beserk: The E_total counter quickly jumped into cosmic regions:



I still dont now what exactly caused the problem, i guess the snprintf routine i use to output the meter readings when polled by my monitoring server is buggy. Anyhow: the meter is back online and running again.