Wednesday, January 15, 2014

Scala/Akka library for serial communication

I like Scala and Akka a lot and am still doing some projects using an Arduino. Akka has a nice new interface for actor based interfacing (see Akka I/O) so I decided to write a little library that bridges the good old RXTX serial port library to it.

It was a rather easy exercise, it only took around 220 lines of code most of which are message definitions. RXTX is still nasty (esp. with regarding the handling of the native libraries), but at least my actor hides to ugly parts.
See my the rxtx-akka-io project on my github profile for the source code and some examples.

Short usage example (inside an akka actor):
override def preStart = IO(Serial) ! Open(port, 9600) 
override def receive = {
  case Opened(operator, _) =>
    println("Connected to port")
    context become open(operator)
}
The operator actor then accepts messages like Write(ByteString) and Close and starts sending Received(ByteArray) messages to the actor that started it.
Failure handling is easy, if something happens the operator actor will crash and leave it to it's parent (the actor that executes the code printed above) to restart it or handle it otherwise.

Happy Hacking!