An avian carrier's blog – Scala Atom feed

Scala programming language
  1. Accessing serial ports the easy way (2011-12-01)

    Every once in a while, I see people having a hard time accessing a RS232 or USB serial port from Java. There exist several solutions to do this in Java:

    • The Java Communications 3.0 API looks awfully old and unmaintained. It is available for Solaris SPARC, Solaris x86, and Linux x86.

    • RXTX is a mix between Java code and C code accessed through the Java native interface. It is hosted on a CVS server and it looks like the 2.2 release will never go out since it got stuck on version 2.2pre2 released in 2009. The last stable version is 2.1.7 from 2006.

    • PureJavaComm is a drop-in replacement for those two libraries, written in Java and using JNA to interface with the system. It is simpler to setup than RXTX, is hosted on GitHub and is actively maintained.

    However, there exist at least one other solution which does not require the use of any external library. This is what I chose to interface a Scala program with a XBee Pro module through a serial interface to interact with my students devices. I also use it to interface the Factor programming language with the same XBee module.

    Every language has a well-defined and well-maintained sockets library, right? So why not simply use socat, a multipurpose relay which is able to bridge many protocols and interfaces such as, in our case, TCP and a serial port?

    I launch socat as

    % socat TCP-LISTEN:4161,fork,reuseaddr FILE:/dev/ttyUSB0,b57600,raw
    

    and what I immediately get is a TCP server listening onto port 4161 and ready to relay any incoming connection to the /dev/ttyUSB0 serial port with a 57600 baud rate. And not only do I have no more concern about accessing the serial port properly, but also I can access a port located on a remote computer as easily by launching socat there instead of locally.

    But what if I want to spy on the TCP/serial relay to see that I send the right codes to the XBee module? socat offers you a choice of command-line options to dump the data in various formats.

    What does the Scala interface look like? I have a XBee abstract class lacking an InputStream to receive the input from the XBee module and an OutputStream to send the output to it. This class is extended into a concrete class using simply:

    import java.net.Socket
    
    class TCPXBee(host: String, port: Int) extends XBee {
    
      private val socket: Socket = new Socket(host, port)
    
      override protected val inStream = socket.getInputStream
      override protected val outStream = socket.getOutputStream
    
      init()
    
    }
    

    socat makes my life easy. It is probably already packaged for your operating system, go and get it! Oh, and did I mention that it works with IPv6 too?

  2. Just because I can (2011-10-11)

    People programming for the Android platform know that you are not supposed to perform lengthy operation in the user interface task. You must create a background task, which will interact with your user interface task through a Handler, or you will use a pre-built AsyncTask to ease the interaction.

    However, if you chose to use Scala instead of Java to build your Android application, you can easily take advantage of its functional nature to build much more exciting constructs to handle this mandatory parallelism. For example, while developing a piece of code to retrieve the state of my city shared bike stations from the network, I wrote a little piece of utility code based on two functions each taking an expression to run: onBG executes something in a background task, and its companion onUI executes something back in the user interface task. Also, when calling onUI, the result of the given expression can later be used from the background task; if needed, it will block until this result is available.

    Here is a short example showing the loading of the bike stations list from the network, then the loading of the state of the first five stations. A progress dialog, part of the user interface, indicates the current state of the background operation. Compare to what you would have needed to write in Java.

        // Execute lengthy loading from the network in a background (BG) task as to not
        // block the user interface (UI) task.
        this.onBG {
          // Create a progress dialog on UI task, and return a pointer to it which, if
          // used, will block as long as needed until the expression has terminated.
          // Otherwise, do not block.
          val progressDialog = this.onUI(ProgressDialog.show(this, "Loading stations",
                                                             "Loading list of stations"))
          try {
            // Load a list of stations from the network (long operation) and keep only
            // five of them.
            val stations = Station.loadFromNetwork.take(5)
    
            // Change the progress dialog so that now it can be used to indicate
            // the progress while station information is loaded from the network.
            // This has to be done on the UI task. Note that this will wait until
            // the progress dialog creation has terminated if needed, as we use
            // the result of the previous "onUI" call.
            this.onUI {
              progressDialog.setIndeterminate(false)
              progressDialog.setMax(stations.size)
            }
    
            // For every station…
            for ((station, index) <- stations.zipWithIndex) {
              // …update the progress dialog on the UI task…
              this.onUI {
                progressDialog.setProgress(index)
                progressDialog.setMessage("Loading station details\n" + station.name)
              }
              // …and load its availability from the network.
              station.reloadAvailability
            }
          } finally {
            // Whatever the completion is (regular or exception), dismiss the
            // progress dialog.
            this.onUI(progressDialog.dismiss)
          }
        }
    

    Why did I write those two functions? Just because, in Scala, I can.

    Don't wait: try Scala today.

  3. Something nice about every language I use (2010-12-09)

    I'll follow Dave Ray and will try to say something nice about a bunch of programming languages I use or have used seriously:

    • Ada – The only language I would trust my life to.

    • C – It gets things done easily in a controlled space when resources are scarce. I use it in many embedded situations, often with FreeRTOS.

    • C++ – Its templating system with specialization beats everything I know. When I worked on Urbi at Gostai, I had a lot of pleasure using it.

    • Erlang – The language to use to develop distributable parallel applications. I wrote many programs for research projects with it.

    • Factor – One of the languages I feel the most comfortable with. I really like the reverse polish notation and the powerful combinators. I use it for many personal and teaching projects.

    • Forth – Forth is one of the languages that I have been liking since the first time I heard about it. Its conciseness, simplicity, grammar and ease of implementation beats almost everything when it comes to size on very small embedded systems. I used it to write a Forth compiler targetting the Microchip PIC16Fxxx microcontrollers family.

    • Haskell – I started using it when I had to send patches for Darcs. I really love monads, and I also love explaining them in class. My window manager configuration is also written in Haskell.

    • J – It is unbeatable if you have RSI and need to type as little characters as possible for a task that can be applied to a whole array. I use it mostly to solve Project Euler problems.

    • Java – Well, everyone knows it so it may be used to explain a simple concept. Is that nice enough?

    • Javascript – Javascript lets us do things in the browser I would not have imagined five years ago. For example, this web page is static but includes Twitter updates and comments, thanks to Javascript. On the server side, I use it within a CouchDB database where I store a whole web application; it dynamically generates iCalendar views for multiple people from data gathered at TVrage.com using their XML API.

    • Python – I can hack anything in a few minutes and still be able to read it later. I wrote a Forth compiler for the Microchip PIC18Fxxx microcontrollers family with it.

    • Ruby – Feels like Python, only more functional and cleaner. I would use it more if I had not been bitten by threading unstability on Sparc64Linux in the past (for the will-spam-for-food.eu.org service we ran with Pierre Beyssac and Thomas Quinot). Ruby helps me run this blog.

    • Scala – There comes a useful, powerful and pleasant to use language targetting the Java virtual machine. I used it to write my HarassMe Android application.

    I probably forgot some languages in the list. However, if I use them, I am sure I can tell something nice about them.