blinkin blue leds with ruby

#!/usr/bin/env ruby

require 'rpi_gpio'

def init
    RPi::GPIO.set_numbering :bcm

    [17,18,27,22].each do |pin|
        RPi::GPIO.setup pin, :as => :output
        RPi::GPIO.set_low pin
    end
end

def cycle
    [17,18,27,22,27,18].each do |pin|
        RPi::GPIO.set_high pin
        sleep (0.25)
        RPi::GPIO.set_low pin
    end
end

init
(1..9).each{ cycle }

RPi::GPIO.reset

This is the Ruby version of my Cylon LED test cycler that I’ve written in various languages on Arch Linux and the Raspberry Pi. This time it was Ruby’s turn to see if I could use it to manipulate the various I/O subsystems on the Pi. Since setting output pins to drive LEDs is the easiest place for me to start, I wrote the code you see above. Before I could make it work I had to install the rpi_gpio gem. To get some idea of how to use it I looked at the GitHub repository for rpi_gpio. The reason for this is to be able to bridge between the Ruby on Rails work I started earlier this week with both input and output I/O. The only other comment I will make is to make sure that the udev rules have been set up to manipulate the I/O as a regular user. Trying to run the code shown above as root will fail, as the installation of rpi_gpio was local to a regular account, not globally installed.

My only comment on rpi_gpio so far is this: I discovered I had to code a set_low immediately after every enabling of a pin as an output, as the pin was enabled high. I consider this a bug, and as it stands it may not be suitable for what I need. If even a microsecond pulse goes out from those pins after being enabled by Ruby then that’s enough to cause a false start on that pin. The Ruby code isn’t something to write home about, just something to do some very basic testing.

running rails + ruby + arch linux arm on raspberry pi 3

screen-shot-2016-10-20-at-10-05-26-pm

I’ve been asked to create a web monitoring application running on a Raspberry Pi (in this case the 3). The requirements are very modest; run a low-traffic web page to monitor another machine next to it, and provide a simple web report on demand across local WiFi. For this particular project I’ve elected to go back in time, as it were, and install Ruby and Rails as the web foundation. And when I say back in time, I’m talking 2007, when I created another embedded system using a milliwatt CMOS 486 clone chip running a custom built Linux kernel with µclib and BusyBox running Ruby and Rails.

This small post documents the steps, in order, for installing Ruby and Rails peculiar to Arch Linux ARM and the Raspberry Pi 3.

First, make sure that Ruby is installed. That’s as simple as ‘sudo pacman -S ruby’, and for the documentation, ‘sudo pacman -S ruby-docs’. Ruby Gems are a part of Ruby, and you can look to see if they’ve been installed with either a ‘gem -v’ or by looking down /usr/lib/ruby.

Second, add the following line to your .bashrc:

  • export PATH=”$(ruby -e ‘print Gem.user_dir’)/bin:$PATH”

Log out, then log back in. Make sure to do all this before you install Rails, or else Very Bad Things will happen when you do install Rails. It took two attempts to install Rails, all because I failed to add that line to my bashrc file before the first attempt. You can read all about RubyGems setup here.

Third, install Rails with ‘gem install rails’. This will install an account local copy of Rails under ~/.gem, specifically ~/.gem/ruby/2.3.0/gems with this version of Gems. Installing a local account copy is no different than what happens with Node.js installations. There’s always a debate about local vs global installation; due to security and my personal paranoia I always prefer local (non-root) account installation to minimize any unintended consequences a global installation might engender.

Fourth, to be able to reach the Ruby instance outside the Raspberry Pi, I modified the file ~/[project]/config/boot.rb and added the following lines of code at the end of the file:

require 'rails/commands/server'

module Rails
    class Server
        def default_options
            super.merge({Port: 8081, Host: '0.0.0.0'})
        end
    end
end

The merge binds the web server to whatever IP address DNS assigns to the Raspberry Pi (‘0.0.0.0’) instead of using localhost as the defult, and changes the port from the default of 3000 to 8081.

Finally, and this is just extra, I made a tiny modification to the default index file at ~/.gem/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/templates/rails/welcome/index.html.erb to add the text “Raspberry Pi 3” in order to drive home that the default web page was in fact coming from the Raspberry Pi 3.

Now on to doing something more useful…

surprise! django runs on arch linux arm on a rasperry pi 3 after all!

Archlinux-icon-crystal-64.svg

tl;dr: It was permissions issues that kept Django from executing properly on Arch ARM and the Raspberry Pi 3. Read on for the details.

Well, looks like I have to walk back that snide comment about Arch running on a Raspberry Pi 3. While I’m certainly no hero, I was irritated considerably by Django’s flagrant failure, enough to find out why. But first, some background.

  1. Django, along with a lot of other Python packages, is located in the system’s site-packages directory. On the RPi 3 running Arch ARM it’s /usr/lib/python3.5/site-packages. The site-packages directory is owned by root (root:root) with permissions 755. Permissions 755 means root can read/write, while group and the world can only read and execute from that directory.
  2. With that kind of ownership I had to install Django with ‘sudo pip install django’ (without the quotes, obviously). After installation every directory had 750 permissions, and every file had 640 permissions, with root:root ownership. That means, using the non-root account alarm, I had no permissions to read anything in the django installation.
  3. And thus any attempt to use django-admin was bound to fail

I don’t have copious amounts of time to work on these kinds of issues. So while I was out working on my honey-do list, while at Trader Joes in the organic produce section, the light went on as to what the probable problem and solution was. Sure enough, when I got home and found a minute to look, that’s when I found the permission settings all wrong. A quick ‘sudo find . -type d -exec chmod 755 {} \+’ and ‘sudo find . -type f -exec chmod 644{}\+’ fixed things up, and I was able to get a quick and dirty Django web server up and running. In fact, to test a capability I’ll need, I tarred up the sample I built on the MBP, secure copied it over to the RPi 3, untarred it there, and got it up and running. Here’s a couple of screen shots of it in action on the RPi 3:

Screen Shot 2016-08-14 at 2.46.50 PMScreen Shot 2016-08-14 at 2.48.01 PMLooks like I’m back in business. The only thing I edited on the RPi 3 was the polls/views.py with vi to change the text output by views.py. Other than that, I simply started it up.

This is the first time I’ve ever had a problem with permissions using pip and Python. In the future I’m going to have to be careful with Arch ARM. It’s a small issue, considering everything else works just fine.

a tale told by an idiot

Windows10Version14393.67I have been wrestling recently with a series of self-imposed requirements that sprang from two personal needs; the first being the development of “sane” native tools and libraries for manipulating Raspberry Pi 3 built-in peripherals (GPIO being at the top of my list), and the second being a way to find a common language and framework that would work across multiple operating systems, those operating systems being Arch Linux ARM, Mac OS X, and Windows 10. And a web framework would be really nice to have because I’m really getting tired of having to use ssh all the time.

So I did a bit of research and decided to focus on Python, specifically version 3.5 and later. That version of Python is available across all those platforms, and appears to work equally well across them. That means that trivial and not-so-trivial Python applications that aren’t platform specific work equally well across all three. That means I can do a good deal of work on either my Samsung running Windows 10 or my MBP, which includes debugging. I would then transfer the code over to the RPi3 and do final integration there.

The problem I ran into was the choice of a Python web framework. For reasons I won’t go into here I decided to install and learn how to use Django. I’ve successfully followed the getting started tutorials on both the MBP and the Samsung. On the MBP I’ve used Homebrew  to install a number of up-to-date software tools, specifically Python 3.5, while on Windows I downloaded and installed Python 3.5 from the Python site. The only comments I have to make about installing Python on Windows 10 are these:

  • Install Python at the root of the C: drive (i.e. C:\Python3.5, for example). This makes the path to Python a lot shorter than where the default is, somewhere in your private user area.
  • Assuming you installed Python in C:\Python3.5 (for example) you should also add the Python Scripts folder to the path, i.e. C:\Python3.5\Scripts. This will put pip and django-admin in the path and make the instructions for using both the same as under Linux and Mac OS X. I don’t know why the tutorial instructions didn’t point this out.

As I said, running the Django utilities works just fine on Mac OS X and Windows 10. Getting Django installed on Arch Linux ARM doesn’t work, either as a pacman package or via pip. There is no package for ARM Arch, and even though the pip install seems to work, trying to create a default site with django-admin on Arch ARM fails, with django-admin complaining there is no django.core. This makes the second major framework failure I’ve run into under Arch ARM, the first being the failure of Express under Node.js. The Express failure was particularly annoying, as it worked about a year ago when I was investigating Express and Node.js on the Raspberry Pi 2. If anything, these failures have proven that the Raspberry Pi 3, at least under Arch Linux ARM, is not the full first-class client that regular installations are.

I suppose I could be a hero (to someone) if I could find and fix the problems I’ve run into on the Raspberry Pi 3, but I don’t feel particularly heroic. I’e gone down multiple paths now with trying to build a full stack of software with a web front end on the RPi 3, and it’s not gone well. One reason for doing the same types of activities on a “regular” computer is to see if the tutorials are repeatable, and they are. It’s trying to move over to the RPi 3 with Arch Linux where it breaks down.

Perhaps it’s time to realize that if I want a better development experience that I need to spend more money and buy a more commercial system than the Raspberry.

As for where the title came from, here it is:

Life’s but a walking shadow, a poor player
That struts and frets his hour upon the stage
And then is heard no more: it is a tale
Told by an idiot, full of sound and fury,
Signifying nothing.
Macbeth, Act 5, Scene 5

The quote about life could just as easily apply to software development.

gpio app evolves, and i come to accept coding in c++11

I am easily seduced by the new. I read about how wonderful something is, and I fall like a sack of potatoes for the sales pitch. In this case I fell for both Go’s and Rust’s sales pitch, without completely thinking things through, like how I would transition complex software already written in one language (C++) into equivalents in either Go or Rust. I also too easily bought into the “better, faster, safer” code argument for both Go and Rust.

I’ve had some time to try out both languages and various Raspberry Pi device frameworks, some of them written in Go, another written in Javascript, and at least one written in C/C++. It turns out that the C/C++ framework, WiringPi, is the most complete, and the one that works best for me. The Javascript framework is a very close second. In spite of some intense personal research into Go and Rust, I’m still a better C++ programmer (or at least, I understand it best) than I am in either Go or Rust. All of this combines to lead me one inevitable decision: write my code in C++ with what works best right now. And if I want “better, faster, safer” software then (re-) learn best C++ coding practices and use them diligently. And not just C++ specific best practices, but good old fashioned common sense best software engineering practices. If there’s one thing I’ve learned over time, it’s that no language will save you from a poor design: above all, KISS.

With that in mind, here’s the latest GPIO manipulation application source.

#include <wiringPi.h>

#include <boost/algorithm/string.hpp>
#include <boost/tokenizer.hpp>

#include <iostream>
#include <fstream>
#include <sstream>

struct glyph {
    unsigned int GPIOpindata = 0;
    int delayInMillis = 0;
};

std::vector<glyph> glyphs;

bool loadBlinkData(std::string const fileName) {
    std::ifstream inFile(fileName);
    glyphs.clear();

    if (not inFile.is_open()) {
        std::cout << "Could not open " << fileName << std::endl;
        return false;
    }

    std::cout << "Using " << fileName << std::endl;
    std::string inLine;

    while (std::getline(inFile, inLine)) {
        boost::trim(inLine);
        if (not inLine.length() or inLine[0] == '#') {
            continue;
        }

        boost::tokenizer<> tokens(inLine);
        glyph g;

        for(auto &&token: tokens) {
            if (token.find("x") != std::string::npos or 
                token.find("X") != std::string::npos) {
                g.GPIOpindata = std::stoul(token, nullptr, 16);
            }
            else {
                g.delayInMillis = std::stoi(token);
            }
        }

        glyphs.push_back(g);
    }

    inFile.close();
    return true;
}

std::string defaultDataFile("blinkdata.csv");

int main (int argc, char *argv[]) {
    // Check to see if we passed another file on the command line.
    // If so, use it instead of the default.
    //
    if (argc > 1) {
        defaultDataFile = argv[1];
    }

    // Look to see if we can open and parse the file.
    // If not, stop.
    //
    if (not loadBlinkData(defaultDataFile)) {
        return 1;
    }

    // The input file was opened and parsed.
    // Now go to work.
    //
    wiringPiSetup();

    pinMode(0, OUTPUT);
    pinMode(1, OUTPUT);
    pinMode(2, OUTPUT);
    pinMode(3, OUTPUT);

    for (int i = 0; i < 5; ++i) { 
        for (auto &&g : glyphs) { 
            // Just a series of shifts and ANDs to create the bit necessary 
            // write out to the GPIO pin. 
            // 
            digitalWrite(0, g.GPIOpindata & 0x1);
            digitalWrite(1, (g.GPIOpindata >> 1 ) & 0x1 );
            digitalWrite(2, (g.GPIOpindata >> 2 ) & 0x1 );
            digitalWrite(3, (g.GPIOpindata >> 3 ) & 0x1 );

            delay(g.delayInMillis);
        }
    }

    // Turn everything off.
    //
    digitalWrite(0, LOW);
    digitalWrite(1, LOW);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);

    return 0;
}

Little improvements abound in this re-write.

  • Idiomatic C++11 is used as much as possible to avoid older C++ hacks (see the use of std::stoul at line 41 to convert the hex data string, for example) and cleaner reading code (see the for loops at lines 38 and 83, for example).
  • I use the One True Brace Style (1TBS) throughout, which frankly is just a variation of K&R brace style (the opening brace is on the same line as code). 1TBS helps these tired old eyes read code more easily. It also helps to minimize errors like Apple’s SSL/TLS “goto fail” bug.
  • More descriptive variable names are used throughout, and variables are declared close to where they’re first needed. Scope actually means something.
  • Rudimentary error checking now takes place, with quick exits that minimize resource usage on various failures. For example, the input data file is checked to see if it can be opened and parsed before any I/O devices are initialized.
  • I performed a static code check with cppcheck to make sure I haven’t missed anything like improperly uninitialized variables.
  • The code is compiled with ‘-Wall’ to get all warnings, and all warnings are treated as errors; they’re corrected.
  • Write the namespace (std:: and boost::) in front of elements explicitly, rather than use the lazy way of declaring a namespace globally with “using namespace namespace” at the top of source. I know exactly what comes  from where, which is quite useful when I revisit code six months after writing it.

It’s barely 100 lines long, but it’s an opportunity to get back into good C++ coding habits and to stay there than go off with a new, and unknown-to-me language.