The Smell of Molten Projects in the Morning

Ed Nisley's Blog: Shop notes, electronics, firmware, machinery, 3D printing, laser cuttery, and curiosities. Contents: 100% human thinking, 0% AI slop.

Tag: RPi

Raspberry Pi

  • Raspberry Pi Streaming Radio Player: Marginally Viable Product

    The least horrible way to get events from the keypad turned out to be a simple non-blocking poll from Python’s select library, then sucking the event input queue dry; the main loop now does what might be grandiosely overstated as cooperative multitasking. Well, hey, it reads lines from mplayer’s output pipe and processes keypad events and doesn’t stall (for very long) and that’s multi enough for me.

    It extracts the stream title from the ICY Info line, but I still haven’t bothered with a display. It may well turn out that this thing doesn’t need a display. The stream title will be enclosed in single quotes, but it may also contain non-escaped and non-paired single quotes (a.k.a. apostrophes): the obvious parsing strategy doesn’t work. I expect titles can contain non-escaped semicolons, too, which will kill the algorithm I’m using stone cold dead. Some try - except armor may be appropriate.

    This code does not tolerate a crappy WiFi connection very well at all. I eventually replaced a long-antenna WiFi adapter with an actual Ethernet cable and all the mysterious problems at the far end of the house Went Away. Soooo this code won’t tolerate random network stream dropouts very well, either; we’ll see how poorly that plays out in practice.

    The hackery to monitor / kill / restart / clean up after mplayer and its pipes come directly from seeing what failed, then whacking that mole in the least intrusive manner possible. While it would be better to wrap a nice abstract model around what mplayer is (assumed to be) doing, it’s not at all clear to me that I can build a sufficiently durable model to be worth the effort. Basically, trying to automate a program designed to be human-interactive is always a recipe for disaster.

    The option for the Backspace / Del key lets you do remote debugging by editing the code to just bail out of the loop instead of shut down. Unedited, it’s a power switch: the Pi turns off all the peripherals and shuts itself down. The key_hold conditional means you must press-and-hold that button to kill the power, but don’t run this on your desktop PC, OK?

    Autostarting the program requires one line in /etc/rc.local:

    sudo -u pi python /home/pi/Streamer.py &
    

    AFAICT, using cron with an @REBOOT line has timing issues with the network being available, but I can’t point to any solid evidence that hacking rc.local waits until the network is up, either. So far, so good.

    I make no apologies for any of the streams; I needed streams behind all the buttons and picked stuff from Xiph’s listing. The AAC+ streams from the Public Domain Project give mplayer a bad bellyache; I think its codecs can’t handle the “+” part of AAC+.

    All in all, not bad for a bit over a hundred lines of code, methinks…

    More fiddling will happen, but we need some continuous experience for that; let the music roll!

    The Python program as a GitHub Gist:

    from evdev import InputDevice,ecodes,KeyEvent
    import subprocess32
    import select
    import re
    import sys
    Media = {'KEY_KP7' : ['Classical',['mplayer','-playlist','http://stream2137.init7.net/listen.pls'%5D%5D,
    'KEY_KP8' : ['Jazz',['mplayer','-playlist','http://stream2138.init7.net/listen.pls'%5D%5D,
    'KEY_KP9' : ['WMHT',['mplayer','http://live.str3am.com:2070/wmht1'%5D%5D,
    'KEY_KP4' : ['Dub 1',['mplayer','-playlist','http://dir.xiph.org/listen/2645/listen.m3u'%5D%5D,
    'KEY_KP5' : ['Dub 2',['mplayer','http://streaming207.radionomy.com:80/MiamiClubMusiccom'%5D%5D,
    'KEY_KP6' : ['WAMC',['mplayer','http://pubint.ic.llnwd.net/stream/pubint_wamc'%5D%5D,
    'KEY_KP1' : ['Oldies 1',['mplayer','http://streaming304.radionomy.com:80/keepfree60s'%5D%5D,
    'KEY_KP2' : ['Oldies 2',['mplayer','http://streaming207.radionomy.com:80/1000Oldies'%5D%5D,
    'KEY_KP3' : ['Soft Rock',['mplayer','http://streaming201.radionomy.com:80/SoftRockRadio'%5D%5D,
    'KEY_KP0' : ['Smooth',['mplayer','http://streaming202.radionomy.com:80/The-Smooth-Lounge'%5D%5D
    }
    CurrentKC = 'KEY_KP7'
    Controls = {'KEY_KPSLASH' : '/',
    'KEY_KPASTERISK' : '*',
    'KEY_KPENTER' : ' ',
    'KEY_KPMINUS' : '<',
    'KEY_KPPLUS' : '>'
    }
    # set up event input and polling
    k=InputDevice('/dev/input/keypad')
    kp = select.poll()
    kp.register(k.fileno(),select.POLLIN + select.POLLPRI + select.POLLERR)
    # set up files for mplayer pipes
    lw = open('/tmp/mp.log','w') # mplayer piped output
    lr = open('/tmp/mp.log','r') # … reading that output
    # Start the default stream
    print 'Starting mplayer on',Media[CurrentKC][0]," -> ",Media[CurrentKC][-1][-1]
    p = subprocess32.Popen(Media[CurrentKC][-1],stdin=subprocess32.PIPE,stdout=lw,stderr=subprocess32.STDOUT)
    print ' … running'
    #— Play the streams
    while True:
    # pluck next line from mplayer and decode it
    text = lr.readline()
    if 'ICY Info: ' in text:
    trkinfo = text.split(';')
    for ln in trkinfo:
    if 'StreamTitle' in ln:
    trkhit = re.search(r"StreamTitle='(.*)'",ln)
    TrackName = trkhit.group(1)
    print 'Track name: ', TrackName
    break
    elif 'Exiting…' in text:
    print 'Got EOF / stream cutoff'
    print ' … killing dead mplayer'
    p.kill()
    print ' … flushing pipes'
    lw.truncate(0)
    print ' … discarding keys'
    while [] != kp.poll(0):
    kev = k.read
    print ' … restarting mplayer: ',Media[CurrentKC][0]
    p = subprocess32.Popen(Media[CurrentKC][-1],stdin=subprocess32.PIPE,stdout=lw,stderr=subprocess32.STDOUT)
    print ' … running'
    continue
    # accept pending events from keypad
    if [] != kp.poll(0):
    kev = k.read()
    for e in kev:
    if e.type == ecodes.EV_KEY:
    kc = KeyEvent(e).keycode
    if kc == 'KEY_NUMLOCK':
    continue
    # print 'Got: ',kc
    if (kc == 'KEY_BACKSPACE') and (KeyEvent(e).keystate == KeyEvent.key_hold):
    if True:
    print 'Backspace = shutdown!'
    p = subprocess32.call(['sudo','shutdown','-HP',"now"])
    else:
    print 'BS = bail from main, ssh to restart!'
    sys.exit(0)
    if KeyEvent(e).keystate != KeyEvent.key_down:
    continue
    if kc in Controls:
    print 'Control:', kc
    try:
    p.stdin.write(Controls[kc])
    except Exception as e:
    print "Can't send control: ",e
    print ' … restarting player: ',Media[CurrentKC][0]
    p = subprocess32.Popen(Media[CurrentKC][-1],stdin=subprocess32.PIPE,stdout=lw,stderr=subprocess32.STDOUT)
    print ' … running'
    if kc in Media:
    print 'Switching stream to ',Media[kc][0]," -> ",Media[kc][-1][-1]
    CurrentKC = kc
    print ' … halting player'
    try:
    p.communicate(input='q')
    except Exception as e:
    print 'Perhaps mplayer died?',e
    print ' … killing it for sure'
    p.kill()
    print ' … flushing pipes'
    lw.truncate(0)
    print ' … restarting player: ',Media[CurrentKC][0]
    p = subprocess32.Popen(Media[CurrentKC][-1],stdin=subprocess32.PIPE,stdout=lw,stderr=subprocess32.STDOUT)
    print ' … running'
    print 'Out of loop!'
    view raw Streamer.py hosted with ❤ by GitHub
  • Streaming Player: Wireless Keypad

    Moving the streaming media player control panel across the Sewing Room for E-Z access:

    Wireless Keypad - colored labels
    Wireless Keypad – colored labels

    Stipulated: garish labels that don’t fit the keys well at all.

    I need more than one stream for testing; the only one that matters is Classical.

    The keypad uses the same 2.4 GHz ISM band as the Raspberry Pi’s Wifi radio, which means holding a key down (which should never happen) puts a dent in mplayer’s cache fill level. Even absent that interference, the WiFi link seems more than a little iffy, probably because it’s at the far end of the house and upstairs from the router.

    Other WiFi devices report that 2.4 GHz RF has trouble punching through the intervening fifty feet of hardwood floor (on the diagonal, the joists amount to a lot of wood) and multiple sets of doubled wallboard sheets; the RPi probably needs a better radio with an actual antenna. I did move the WiFi control channel away from the default used by the (relatively distant) neighbors, which seemed to improve its disposition.

  • Raspberry Pi Streaming Radio Player: Minimum Viable Product

    With the numeric keypad producing events, and the USB audio box producing sound, the next steps involve starting mplayer through Python’s subprocess interface and feeding keystrokes into it.

    There’s not much to it:

    As much hardware doc as you need:

    RPi Streaming Player - first lashup
    RPi Streaming Player – first lashup

    The green plug leads off to a set of decent-quality PC speakers with far more bass drive than seems absolutely necessary in this context. The usual eBay vendor bungled an order for the adapter between the RCA line-out jacks and the 3.5 mm plug that will avoid driving the speakers from the UCA202’s headphone monitor output; I doubt that will make any audible difference. If you need an adapter with XLR female to 1/4 inch mono, let me know…

    The keypad labels provide all the UI documentation there is:

    Numeric Keypad - stream labels
    Numeric Keypad – stream labels

    The Python source code as a GitHub Gist:

    from evdev import InputDevice,ecodes,KeyEvent
    import subprocess32
    Media = {'KEY_KP7' : ['mplayer','http://relay.publicdomainproject.org:80/classical.aac'%5D,
    'KEY_KP8' : ['mplayer','http://relay.publicdomainproject.org:80/jazz_swing.aac'%5D,
    'KEY_KP9' : ['mplayer','http://live.str3am.com:2070/wmht1'%5D,
    'KEY_KP6' : ['mplayer','http://pubint.ic.llnwd.net/stream/pubint_wamc'%5D,
    'KEY_KP1' : ['mplayer','-playlist','http://dir.xiph.org/listen/5423257/listen.m3u'%5D,
    'KEY_KP2' : ['mplayer','-playlist','http://dir.xiph.org/listen/5197460/listen.m3u'%5D,
    'KEY_KP3' : ['mplayer','-playlist','http://dir.xiph.org/listen/5372471/listen.m3u'%5D,
    'KEY_KP0' : ['mplayer','-playlist','http://dir.xiph.org/listen/5420157/listen.m3u'%5D
    }
    Controls = {'KEY_KPSLASH' : '/',
    'KEY_KPASTERISK' : '*',
    'KEY_KPDOT' : ' '
    }
    k=InputDevice('/dev/input/keypad')
    print 'Starting mplayer'
    p = subprocess32.Popen(Media['KEY_KP7'],stdin=subprocess32.PIPE)
    print ' … running'
    for e in k.read_loop():
    if (e.type == ecodes.EV_KEY) and (KeyEvent(e).keystate == 1):
    kc = KeyEvent(e).keycode
    if kc == 'KEY_NUMLOCK':
    continue
    print "Got: ",kc
    if kc == 'KEY_BACKSPACE':
    print 'Backspace = shutdown!'
    p = subprocess32.call(['sudo','halt'])
    break
    if kc in Controls:
    print 'Control:', kc
    p.stdin.write(Controls[kc])
    if kc in Media:
    print 'Switching stream to ',Media[kc]
    print ' … halting'
    p.communicate(input='q')
    print ' … restarting'
    p = subprocess32.Popen(Media[kc],stdin=subprocess32.PIPE)
    print ' … running'
    print "Out of loop!"

    The Media dictionary relates keycodes with the command line parameters required to fire mplayer at the streaming stations. With that running, the Controls dictionary turns keycodes into mplayer keyboard controls.

    There’s no display: you have no idea what’s going on. I must start the program manually through an ssh session and can watch mplayer‘s console output.

    Poking the Halt button forcibly halts the RPi, after which you squeeze the Reset button to reboot the thing. There’s no indication that it’s running, other than sound coming out of the speakers, and no way to tell it fell of the rails other than through the ssh session.

    The loop blocks on events, so it can’t also extract stream titles from the (not yet implemented) mplayer stdout pipe / file and paste them on the (missing) display; that’s gotta go.

    There’s a lot not to like about all that, of course, but it’s in the tradition of getting something working to discover how it fails and, in this case, how it sounds, which is even more important.

  • Raspberry Pi: USB Keypad Via evdev

    The general idea is to use keystrokes plucked from a cheap numeric keypad to control mplayer, with the intent of replacing some defunct CD players and radios and suchlike. The keypads look about like you’d expect:

    Numeric keypads
    Numeric keypads

    The keypad layouts are, of course, slightly different (19 vs 18 keys!) and they behave differently with regard to their NumLock state, but at least they produce the same scancodes for the corresponding keys. The black (wired) keypad has a 000 button that sends three 0 events in quick succession, which isn’t particularly useful in this application.

    With the appropriate udev rule in full effect, this Python program chews its way through incoming events and reports only the key-down events that will eventually be useful:

    from evdev import InputDevice,ecodes,KeyEvent
    k=InputDevice('/dev/input/keypad')
    for e in k.read_loop():
    if (e.type == ecodes.EV_KEY) and (KeyEvent(e).keystate == 1):
    if (KeyEvent(e).keycode == 'KEY_NUMLOCK'):
    continue # we don't care about the NumLock state
    else:
    print KeyEvent(e).scancode, KeyEvent(e).keycode

    Pressing the keys on the white keypad in an obvious sequence produces the expected result:

    82 KEY_KP0
    79 KEY_KP1
    80 KEY_KP2
    81 KEY_KP3
    75 KEY_KP4
    76 KEY_KP5
    77 KEY_KP6
    71 KEY_KP7
    72 KEY_KP8
    73 KEY_KP9
    98 KEY_KPSLASH
    55 KEY_KPASTERISK
    14 KEY_BACKSPACE
    74 KEY_KPMINUS
    78 KEY_KPPLUS
    96 KEY_KPENTER
    83 KEY_KPDOT
    

    Observations

    • KeyEvent(e).keycode is a string: 'KEY_KP0'
    • e.type is numeric, so just compare against evcodes.EV_KEY
    • KeyEvent(e).scancode is the numeric key identifier
    • KeyEvent(e).keystate = 1 for the initial press
    • Those KeyEvent(e).key_down/up/hold values don’t change

    If you can type KEY_KP0 correctly, wrapping it in quotes isn’t such a big stretch, so I don’t see much point to running scancodes through ecodes.KEY[KeyEvent(e).scancode] just to compare the enumerations.

    I’m surely missing something Pythonic, but I don’t get the point of attaching key_down/up/hold constants to the key event class. I suppose that accounts for changed numeric values inside inherited classes, but … sheesh.

    Anyhow, that loop looks like a good starting point.

  • Improving Avahi Startup Speed

    At least on my network, disabling the IPv6 functions makes Avahi start up faster. You do that by tweaking the obvious IPV6 line in /etc/avahi/avahi-daemon.conf:

    use-ipv4=yes
    use-ipv6=no
    

    It’s also useful to disable power management in the USB WiFi dongle by adding /etc/modprobe.d/8192cu.conf:

    # Disable power saving
    options 8192cu rtw_power_mgnt=0 rtw_enusbss=0
    
  • UDEV Rules for Cheap Numeric Keypads

    I’m thinking of numeric keypads as control panels for Raspberry Pi projects like a simpleminded streaming radio player, so:

    Numeric keypads
    Numeric keypads

    Sorta like wedding pictures: you can expose for the groom-in-black or the bride-in-white, but not both at the same time.

    The wireless keypad does not have a slot for the USB radio: put ’em in a bag to keep ’em together when not in use.

    The general idea is to create a standard name (/dev/input/keypad) for either keypad when it gets plugged in, so the program need not figure out the device name from first principles. This being an embedded system, I can ensure only one keypad will be plugged in at any one time.

    The wired keypad has an odd name that makes a certain perverse sense:

    cat /proc/bus/input/devices
    ... snippage ...
    I: Bus=0003 Vendor=13ba Product=0001 Version=0110
    N: Name="HID 13ba:0001"
    P: Phys=usb-20980000.usb-1.4/input0
    S: Sysfs=/devices/platform/soc/20980000.usb/usb1/1-1/1-1.4/1-1.4:1.0/0003:13BA:0001.0007/input/input6
    U: Uniq=
    H: Handlers=sysrq kbd event0
    B: PROP=0
    B: EV=120013
    B: KEY=10000 7 ff800000 7ff febeffdf f3cfffff ffffffff fffffffe
    B: MSC=10
    B: LED=7
    

    It’s a single-function device, so this rule in /etc/udev/rules.d/KeyPad.rules suffices:

    ATTRS{name}=="HID 13ba:0001", SYMLINK+="input/keypad"
    

    Using the Vendor and Device ID strings (13ba:0001) might make more sense.

    The wireless keypad isn’t nearly that easy, because it reports for duty as both a keyboard and a mouse:

    cat /proc/bus/input/devices
    ... snippage ...
    I: Bus=0003 Vendor=062a Product=4101 Version=0110
    N: Name="MOSART Semi. 2.4G Keyboard Mouse"
    P: Phys=usb-20980000.usb-1.4/input0
    S: Sysfs=/devices/platform/soc/20980000.usb/usb1/1-1/1-1.4/1-1.4:1.0/0003:062A:4101.0008/input/input7
    U: Uniq=
    H: Handlers=sysrq kbd event0
    B: PROP=0
    B: EV=120013
    B: KEY=10000 7 ff9f207a c14057ff febeffdf ffefffff ffffffff fffffffe
    B: MSC=10
    B: LED=7
    
    I: Bus=0003 Vendor=062a Product=4101 Version=0110
    N: Name="MOSART Semi. 2.4G Keyboard Mouse"
    P: Phys=usb-20980000.usb-1.4/input1
    S: Sysfs=/devices/platform/soc/20980000.usb/usb1/1-1/1-1.4/1-1.4:1.1/0003:062A:4101.0009/input/input8
    U: Uniq=
    H: Handlers=kbd mouse0 event2
    B: PROP=0
    B: EV=1f
    B: KEY=3f 3007f 0 0 0 0 483ffff 17aff32d bf544446 0 0 1f0001 130f93 8b17c000 677bfa d941dfed 9ed680 4400 0 10000002
    B: REL=1c3
    B: ABS=1f01 0
    B: MSC=10
    

    That may be because the 0x06a2 Vendor ID was cloned (that’s pronounced “ripped-off”) from Creative Labs. My guess is they ripped the entire chipset, because the 0x4101 device ID came from a Creative Labs wireless keyboard + mouse:

    lsusb
    ... snippage ...
    Bus 001 Device 011: ID 062a:4101 Creative Labs
    ... snippage ...
    

    Because it’s a dual-mode wireless device, we need more information to create the corresponding udev rule. The keyboard part appears (on this boot) as event0, which we find thusly:

    ll /dev/input/by-id
    total 0
    lrwxrwxrwx 1 root root 9 Feb  5 17:39 usb-Burr-Brown_from_TI_USB_Audio_CODEC-event-if03 -> ../event1
    lrwxrwxrwx 1 root root 9 Feb  5 17:39 usb-MOSART_Semi._2.4G_Keyboard_Mouse-event-kbd -> ../event0
    lrwxrwxrwx 1 root root 9 Feb  5 17:39 usb-MOSART_Semi._2.4G_Keyboard_Mouse-if01-event-mouse -> ../event2
    lrwxrwxrwx 1 root root 9 Feb  5 17:39 usb-MOSART_Semi._2.4G_Keyboard_Mouse-if01-mouse -> ../mouse0
    

    Some spelunking suggests using the environment variables set up by the default udev rules, which we find thusly:

    udevadm test /sys/class/input/event0
    ... vast snippage ...
    .INPUT_CLASS=kbd
    ACTION=add
    DEVLINKS=/dev/input/by-id/usb-MOSART_Semi._2.4G_Keyboard_Mouse-event-kbd /dev/input/by-path/platform-20980000.usb-usb-0:1.4:1.0-event-kbd
    DEVNAME=/dev/input/event0
    DEVPATH=/devices/platform/soc/20980000.usb/usb1/1-1/1-1.4/1-1.4:1.0/0003:062A:4101.0012/input/input17/event0
    ID_BUS=usb
    ID_INPUT=1
    ID_INPUT_KEY=1
    ID_INPUT_KEYBOARD=1
    ID_MODEL=2.4G_Keyboard_Mouse
    ID_MODEL_ENC=2.4G\x20Keyboard\x20Mouse
    ID_MODEL_ID=4101
    ID_PATH=platform-20980000.usb-usb-0:1.4:1.0
    ID_PATH_TAG=platform-20980000_usb-usb-0_1_4_1_0
    ID_REVISION=0108
    ID_SERIAL=MOSART_Semi._2.4G_Keyboard_Mouse
    ID_TYPE=hid
    ID_USB_DRIVER=usbhid
    ID_USB_INTERFACES=:030101:030102:
    ID_USB_INTERFACE_NUM=00
    ID_VENDOR=MOSART_Semi.
    ID_VENDOR_ENC=MOSART\x20Semi.
    ID_VENDOR_ID=062a
    MAJOR=13
    MINOR=64
    SUBSYSTEM=input
    ... more snippage ...
    

    So when that vendor and device appear with ID_INPUT_KEYBOARD set, we can create a useful symlink using this rule in /etc/udev/rules.d/KeyPad.rules:

    ATTRS{idVendor}=="062a", ATTRS{idProduct}=="4101", ENV{ID_INPUT_KEYBOARD}=="1", SYMLINK+="input/keypad"
    

    Because only one keypad will be plugged in at any one time, the /etc/udev/rules.d/KeyPad.rules file can contain both rules:

    ATTRS{name}=="HID 13ba:0001", SYMLINK+="input/keypad"
    ATTRS{idVendor}=="062a", ATTRS{idProduct}=="4101", ENV{ID_INPUT_KEYBOARD}=="1", SYMLINK+="input/keypad"
    

    Reload the rules and fire them off:

    sudo udevadm control --reload
    sudo udevadm trigger
    

    And then It Just Works:

    ll /dev/input/by-id
    total 0
    lrwxrwxrwx 1 root root 9 Feb  5 17:39 usb-Burr-Brown_from_TI_USB_Audio_CODEC-event-if03 -> ../event1
    lrwxrwxrwx 1 root root 9 Feb  5 19:03 usb-MOSART_Semi._2.4G_Keyboard_Mouse-event-kbd -> ../event0
    lrwxrwxrwx 1 root root 9 Feb  5 19:03 usb-MOSART_Semi._2.4G_Keyboard_Mouse-if01-event-mouse -> ../event2
    lrwxrwxrwx 1 root root 9 Feb  5 19:03 usb-MOSART_Semi._2.4G_Keyboard_Mouse-if01-mouse -> ../mouse0ll /dev/input
    
    ll /dev/input
    total 0
    drwxr-xr-x 2 root root     120 Feb  5 19:03 by-id
    drwxr-xr-x 2 root root     120 Feb  5 19:03 by-path
    crw-rw---- 1 root input 13, 64 Feb  5 19:03 event0
    crw-rw---- 1 root input 13, 65 Feb  5 17:39 event1
    crw-rw---- 1 root input 13, 66 Feb  5 19:03 event2
    lrwxrwxrwx 1 root root       6 Feb  5 19:03 keypad -> event0
    crw-rw---- 1 root input 13, 63 Feb  5 17:39 mice
    crw-rw---- 1 root input 13, 32 Feb  5 19:03 mouse0
    

    My configuration hand is strong

    Note: Once again, I manually restored the source code after the WordPress “improved” editor shredded it by replacing all the double-quote and greater-than symbols inside the “protected” sourcecode blocks with their HTML-escaped equivalents. Some breakage may remain and, as always, WP can shred sourcecode blocks even if I don’t edit the post. They’ve (apparently) banned me from contacting Support, because of an intemperate rant based on years of having them ignore this (and other) problems. I didn’t expect any real help, so this isn’t much of a step backwards in terms of actual support …

  • Raspberry Pi: Jessie Lite Setup for Streaming Audio

    As a first pass at a featureless box that simply streams music from various sources, I set up a Raspberry Pi with a Jessie Lite Raspbian image. I’m mildly astonished that they use dd to transfer the image to the MicroSD card, but it certainly cuts out a whole bunch of felgercarb that comes with a more user-friendly interface.

    I used dcfldd (for progress reports while copying) and verify the copied image:

    sudo dcfldd statusinterval=10 bs=4M if=/mnt/diskimages/ISOs/Raspberry\ Pi/2015-11-21-raspbian-jessie-lite.img of=/dev/sdb
    sudo dcfldd statusinterval=10 bs=4M if=/dev/sdb of=/tmp/rpi.img count=350
    truncate --reference /mnt/diskimages/ISOs/Raspberry\ Pi/2015-11-21-raspbian-jessie-lite.img /tmp/rpi.img
    diff -s /tmp/rpi.img /mnt/diskimages/ISOs/Raspberry\ Pi/2015-11-21-raspbian-jessie-lite.img
    

    That fits neatly on a minuscule 2 GB MicroSD card:

    df -h
    Filesystem      Size  Used Avail Use% Mounted on
    /dev/root       1.8G  1.1G  549M  67% /
    devtmpfs        214M     0  214M   0% /dev
    tmpfs           218M     0  218M   0% /dev/shm
    tmpfs           218M  4.5M  213M   3% /run
    tmpfs           5.0M  4.0K  5.0M   1% /run/lock
    tmpfs           218M     0  218M   0% /sys/fs/cgroup
    /dev/mmcblk0p1   60M   20M   41M  34% /boot
    

    Set the name of the Raspberry Pi to something memorable, perhaps streamer1.

    Disable IPV6, because nothing around here supports it, by tweaking /etc/modprobe.d/ipv6.conf:

    alias ipv6 off
    

    Enable the USB WiFi dongle by adding network credentials to /etc/wpa_supplicant/wpa_supplicant.conf:

    ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
    update_config=1
    
    network={
     ssid="your network SSID goes here"
     psk="pick your own"
    }
    

    Nowadays, there’s no need for a fixed IP address, because after adding your public key to the (empty) list in ~/.ssh/authorized_keys, you can sign in using a magic alias:

    ssh -p12345 pi@streamer1.local
    

    I have absolutely no idea how that works, nor how to find out. If it ever stops working, I’m doomed.

    The Raspberry Pi Model B+ has “improved” audio that, to Mary’s ears, comes across as pure crap; even my deflicted ears can hear low-level hissing and bad distortion at moderate volumes. An old Creative Labs Sound Blaster USB box sidesteps that problem, but requires a tweak in /etc/asound.conf to route the audio to the proper destination:

    # Make USB sound gadget the default output
    
    pcm.!default {
     type hw card 1
    }
    ctl.!default {
     type hw card 1
    }
    

    ALSA then seems to default to the wrong channel (or something), although this tweak in the middle of /usr/share/alsa/alsa.conf may not be needed:

    #pcm.front cards.pcm.front
    pcm.front cards.pcm.default
    

    Good old mplayer seems to handle everything involved in streaming audio from the Interwebs.

    Set up blank /etc/mplayer/input.conf and ~/.mplayer/input.conf files to eliminate kvetching:

    # Dummy file to quiet the "not found" error message
    

    Set up ~/.mplayer/config thusly:

    prefer-ipv4=true
    novideo=true
    #ao=alsa:device=hw=1.0
    ao=alsa
    format=s16le
    #mixer-channel=Master
    softvol=true
    volume=25
    quiet=true
    

    The commented-out ao option will force the output to the USB gadget if you want to route the default audio to the built-in headphone jack or HDMI output.

    Telling mplayer to use its own software volume control eliminates a whole bunch of screwing around with the ALSA mixer configuration.

    The quiet option silences the buffer progress display, while still showing the station ID and track information.

    With that in hand, the Public Domain Project has a classical music stream that is strictly from noncommercial:

    mplayer -playlist http://relay.publicdomainproject.org/classical.aac.m3u
    

    Send them a sack of money if you like them as much as we do.

    By contrast, the local NPR station comes across as talk radio:

    mplayer http://live.str3am.com:2070/wmht1
    

    You can’t feed nested playlists into mplayer, but fetching the contents of the stream playlists produces a one-station-per-line playlist file that one might call RadioList.txt:

    http://relay.publicdomainproject.org:80/classical.aac
    http://relay.publicdomainproject.org:80/jazz_swing.aac
    http://live.str3am.com:2070/wmht1
    

    So far, I’ve been manually starting mplayer just to get a feel for reliability and suchlike, but the setup really needs an autostart option with some user-friendly way to select various streams, plus a way to cleanly halt the system. A USB numeric keypad may be in order, rather than dinking around with discrete buttons and similar nonsense.

    There exists a horrible hack to transfer the stream metadata from mplayer onto an LCD, but I’m flat-out not using PHP or Perl. Perhaps the Python subprocess management module will suffice to auto-start a Python program that:

    • starts mplayer with the default playlist
    • parses mplayer’s piped output
    • updates the LCD accordingly
    • reads / translates keypad input

    This being a Pi, not an Arduino, one could actually use a touchscreen LCD without plumbing the depths of absurdity, but that starts looking like a lot of work…