Labels

Linux (39) Thinkpads (4) lego (12) pi (20)
Showing posts with label pi. Show all posts
Showing posts with label pi. Show all posts

Friday, 7 March 2014

Debugging XBMC Plugins

I've been learning XBMC plugin development over the past few months.  I thought it would be a good time to review my remote debugging configuration.  When I had started setting up a debugging environment, I discovered the information available was fragmented and obsolete.

A helpful source is HOW-TO:Debug Python Scripts with Eclipse.  I will refer to it throughout.

Development Environment (IDE)


You can do a lot with just using gedit (with it's python syntax highlighting).  But when things get more complicated, you'll need a place to debug.  An IDE that I've used before, on Java and Perl projects, was Eclipse.  Eclipse has a PyDev plugin available, that can be easily installed through the Updates (Help...Install New Software), which is required to add Python integrated functionality to Eclipse.  Because I didn't have Eclipse installed on my particular current system, I decided to opt for downloading LiClipse instead.  It is "lightweight" and has PyDev already installed. You'll need a Python interpreter installed -- not an issue on most Linux systems.  XBMC also uses your native Linux Python interpreter.

Refer to section 2 in HOW-TO:Debug Python Scripts with Eclipse for setting up PyDev within XBMC.

Setup Workspace

I have all my XBMC plugins located in a particular development folder named development/xbmc.  I simply setup my workspace to this folder.  For each plugin, represented by single subfolder for each (such as XBMC-pluginname), I simply go to File -> New, PyDev Project.  Give the project the appropriate name (XBMC-pluginname), select Python for Project type.  Select Grammar Version 2.7.  For Interpreter, select Default. Click on the "Click here to configure an interpreter not listed".  In the upper right pane, click the Quick Auto-Config, which will configure an interpreter for you.  If you have multiple Python Interpreters installed, repeat until the required version is created.

Before clicking the Finish button, change the radio button to "Don't configure PYTHONPATH (to be done manually later on)".


Refer to section 3 in HOW-TO:Debug Python Scripts with Eclipse for more assistance.  This part of the Wiki is out-of-date, however.

Setup Pysrc (for remote-debugging)

If you want to remote-debug your plugin (that is step through your code while running), you will need to do some further setup.  First, you need to locate the pysrc library files that came with your PyDev install.  If you do a (find . | grep pysrc) from within your Eclipse install, you should find them located in plugins org.python.pydev_3... folder.  Mine were located at ./plugins/org.python.pydev_3.3.3.201401272005/pysrc/.

Next, you'll need to find the global library location for you Python interpreter.   You can do so by running the following:

python -c "from distutils.sysconfig import *; print(get_python_lib())"
My path was /usr/lib/python2.7/dist-packages.  Copy the pysrc folder into this noted folder (you'll need to be root).  

You'll also need to create an empty file called __init__.py within this pysrc folder ( /usr/lib/python2.7/dist-packages/pysrc).  This will allow XBMC transverse into it.

Modify Your XBMC Plugin

To enable remote-debugging to your application, you will need to add some code to your plugin (say into your default.py, below the import statements).  Code I've put in mine resemble this:

try:
    remote_debugger = addon.getSetting('remote_debugger')
    remote_debugger_host = addon.getSetting('remote_debugger_host')

    # append pydev remote debugger
    if remote_debugger == 'true':
        # Make pydev debugger works for auto reload.
        # Note pydevd module need to be copied in XBMC\system\python\Lib\pysrc
        import pysrc.pydevd as pydevd
        # stdoutToServer and stderrToServer redirect stdout and stderr to eclipse console
        pydevd.settrace(remote_debugger_host, stdoutToServer=True, stderrToServer=True)
except ImportError:
    sys.stderr.write("Error: " + "You must add org.python.pydev.debug.pysrc to your PYTHONPATH.")
    sys.exit(1)
except :
    pass
The code will look for the parameter "remote_debugger" and "remote_debugger_host" in your settings.xml file.  If neither is found, an exception will be thrown, and the debugging will be disabled.  This will allow you to maintain one version of your code.  You could use a constant variable instead, but then you'd need to set it somewhere.  I see others implementing a variable like REMOTE_DEBUG and then setting it True or False in the same class, but if you forgot to switch it to False, and push your code out, it'll fail if someone deploys it.  I found my approach elegant, as the debugger code will be inactive unless the user adds the following two lines to their settings.xml:

    <setting id="remote_debugger" value="true" />
    <setting id="remote_debugger_host" value="localhost" />

The remote_debugger_host allows you to use a remote system for debugging, rather than using the same machine.  This allows you to debug your plugin on a Raspberry Pi and debug it using your laptop.  If you are debugging on the same device (laptop running XBMC), then you can leave this as localhost.  Otherwise, change it to your IP of your debugging machine.

The above code was adapted from  HOW-TO:Debug Python Scripts with Eclipse .


Raspberry Pi for Debugging


Just like you setup pysrc earlier on your computer, if you want to run your plugin from a device, such as Raspberry Pi, to remote-debug, you'll need to copy the pysrc folder, found earlier, to your Raspberry Pi.  Follow the same steps under Setup Pysrc, copying the source folder from your computer with Eclipse or LiClipse installed, to your device.  In my case, my Raspberry Pi used the same dist-packages folder (so I copied to usr/lib/python2.7/dist-packages/pysrc).

You may need to add port 5678 to your computer's firewall to allow inbound connections from your debugging device.


Adding PyDev Debugger to your View


There are several ways of accomplishing this.  I prefer going to Window -> Customize Perspective, selecting Command Groups Availability and checkboxing "PyDev Debug".  This will add a PyDev menu with the buttons "Start Debug Server" and "Stop Debug Server" to my Eclipse menu.


Actually Doing the Remote-Debugging...


To start the debugger, I flip to Debug Perspective, and then click the Start Debug Server from PyDev menu.  In the Debug Server window, you'll see "Debug Server at port: 5678". 

Now you can open XBMC.  If you have the remote-debugger code added to your plugin AND have the remote_debugger and remote_debugger_host set in settings.xml, if you try to load the plugin in XBMC, it should try to communicate to the Eclipse debugger.  If it fails to connect to the debugger, it'll push a 110 Connection Failed to the xbmc.log file.  If you see a "You must add org.python.pydev.debug.pysrc to your PYTHONPATH" error, that means the pysrc isn't accessible on your XBMC device (did you add the pysrc folder to the dist-packages folder?  did you include an empty __init__.py  file within that directory?).

If it is working, XBMC should "halt" while your debugger is passed control.  In the Debug panel, you should see an unknown with MainThread show up.  This represents the session running on your XBMC device.  You can now step through the code using standard debugging techniques.  You can also simply "Resume" (F8) to continue running to completion the plugin.



Refer to HOW-TO:Debug Python Scripts with Eclipse for further advise on debugging.

Have fun :) 

Tuesday, 21 January 2014

Re-purposing Old SD Cards for Booting a Raspberry Pi off USB

My server pi machine has a SanDisk Ultra 32GB card for which has a standard Raspbian install.  I found shortly after putting the system together, that I found it more stable to run the linux directly off the attached USB hard drive (for which I always mount).  I created a linux OS-partition on the USB drive (size 16GB).  I rsynced the OS from the SD card to the USB OS-partition.

The design of the Raspberry Pi insists on booting off the SD card.  Once the system is bootstrapped, it can boot of USB or SD card.  The bootstrap partition is very small (59MB).  There is no sense using a full 32GB card just for bootstrapping.

I found an old 32MB (yes, Megabytes) micro-SD card and an even smaller, 16MB SD card.  The bootstrap partition on the standard image 32GB card is actually 18MB.  However, with inspection, I noticed there is a 9MB kernel_emergency boot image contained on it.  I would hazard a guess that this boot image would be booted from as a "safe-mode" option if an upgrade (or other activity) causes the default kernel boot image to become inoperable (the default kernel boot image is only 2.8MB).  If I exclude the kernel_emergency boot image, I'll be able to fit the partition on the SD card without an issue.

Backup the Data off the 32GB SD Card


Looking at the data from the 32GB SD card:

Disk /dev/mmcblk0: 31.9 GB, 31914983424 bytes
4 heads, 16 sectors/track, 973968 cylinders, total 62333952 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00014d34

        Device Boot      Start         End      Blocks   Id  System
/dev/mmcblk0p1            8192      122879       57344    c  W95 FAT32 (LBA)
/dev/mmcblk0p2          122880    62333951    31105536   83  Linux

The MBR is stored at /dev/mmcblk0, the bootstrap partition is a FAT partition (/dev/mmcblk0p1), and the linux OS-partition is /dev/mmcblk0p2.

Reminder that the dd command will most likely require root access -- so run them as root or use sudo.  When copying an OS-partition, as I've done below, run the rsync using root or use sudo, to ensure all the root-restricted files are transfered.

Backup the MBR


The first step is to backup the MBR off the 32GB SD card.

This can be accomplished by running dd:

dd if=/dev/mmcblk0 of=/u01/sd_pi_mbr.iso bs=512 count=1
The MBR is actually a 512MB sector at /dev/mmcblk0.  This is where the boot sector is, along with the partition table.  Depending on the card reader you are using, it'll either appear as the preceeding device, but it could also appear as a /dev/sda, etc device.  Run fdisk -l to verify the device [ensure that you are not selecting the wrong device].

A little background information on the MBR.  The bootstrap part of the MBR is contained in the first 446 bytes (this explains one of the restore commands that follows).  The partition table data is stored in the proceeding 64 bytes (unless the destined SD card is identical in size and partition layout, we won't restore this part of the MBR).  The MBR signature is the last 2 bytes (again, the destined SD card is identical in size and partition layout, we won't restore this part of the MBR).

Backup the Bootstrap Partition


The second step is to backup the bootstrap partition off the 32GB SD card.

This can be accomplished by running dd:

dd if=/dev/mmcblk0p2 of=/u01/sd_pi_boot.iso
In my case, I'll be modifying the existing bootstrap to exclude the kernel_emergency.img.  Therefore, I ended up mounting /dev/mmcblk0p1 and copy the contents of the filesystem to a folder called sd_pi_boot, excluding the kernel_emergency.img.  The resulting is a folder < 10MB in size, which will clearly fit on my 16MB SD card.

Backup the OS-Partition

You'll need to copy the OS-partition over to the eventual destination device eventually.  In my case, it'll be a USB hard drive, and not the SD card.  You can either use dd to take a backup of the image (dd if=/dev/mmcblk0p2 of=/u01/sd_pi_os.iso) or you can copy the files.  I've copied it to the destination location using rsync.  I could also make a image backup and restore of the filesystem using dd and then resize the partition to occupy the entire destination partition size, but I find it faster and with fewer steps to just mound the filesystem on the SD card and using the rsync -avix command to create a mirror copy of the filesystem [reminder to use root or sudo].


Format and Partition the Destination SD Card


The first step is to ready your SD card.  Format the card with a MBR using a Disk Utility to fdisk.  Then create a FAT partition on the card using the same tool (in my case with the 16MB card, I create a partition the full size of the card).

Restore the MBR


The next step is to restore the MBR onto the new SD card.

This can be accomplished by running dd:

dd if=/u01/sd_pi_mbr.iso of=/dev/mmcblk0 bs=446 count=1
Take note of the bs parameter of 446.  Because the new card is of different size (and different partition sizes) then the original, we restore the "bootstrap" part of the MBR only -- we don't want to overwrite the partition table or MBR signature that we created in the proceeding step.

Restore the OS-Partition to your USB device [or other destination]

You'll need to copy the OS-partition over to the eventual destination device.  In my case, it'll be a USB hard drive, and not the SD card.  Either use dd to restore the filesystem image or use the rsync -avix command to create a mirror copy of the filesystem from your backup [reminder to use root or sudo].

Restore the Bootstrap Partition


The next step is to restore the bootstrap partition.

This can be accomplished by running dd:

dd if=/u01/sd_pi_boot.iso of=/dev/mmcblk0p2
In my case, I'll be modifying the existing bootstrap to exclude the kernel_emergency.img.  Therefore, I use copy over the files from a backup folder sd_pi_boot instead of using dd.

I end up with a bootstrap partition containing the following files:

bootcode.bin  cmdline.txt  config.txt  fixup_cd.dat  fixup.dat  fixup_x.dat  issue.txt   kernel.img  start_cd.elf  start.elf  start_x.elf

Modify the OS-Partition Boot Parameter



On the resulting SD card, I need to instruct the bootstrap where to load the OS-partition on boot up.  These startup details are contained in the file cmdline.txt.

The original file contains the following:

dwc_otg.lpm_enable=0 console=ttyAMA0,115200 kgdboc=ttyAMA0,115200 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline rootwait

The OS-partition, more formally known as the root partition, is noted as /dev/mmcblk0p2, which was the original location.  This parameter will need to be updated with the new destination.  In my situation, I restored this to a USB hard drive.  It was not the primary partition on the drive (as it was added after the drive was originally partitioned).  Therefore, in my case, the partition is  /dev/sda3.  If it is your primary partition on the first hard drive connected to the Raspberry Pi, then it'll most likely be /dev/sda1 instead.

My resulting cmdline.txt is as follows:

dwc_otg.lpm_enable=0 console=ttyAMA0,115200 kgdboc=ttyAMA0,115200 console=tty1 root=/dev/sda3 rootfstype=ext4 elevator=deadline rootwait



That's it!  Now perform a sync command (to ensure the write buffers are flushed to the SD card when you eject it), and then safely unmount the partitions on the SD card and eject the SD card from your computer.  Plug it into the Raspberry Pi along with your USB hard drive [or other device containing your new OS-partition].  When you power on the Pi, it should start accessing the partition containing your OS-partition within 3 seconds of receiving power.  In my case, my system is headless (without screen), so I use the LEDs to confirm what is happening.  I notice the hard drive LED starts blinking read (as opposed to green) within 2 seconds of the Pi being powered on, validating that I've done everything properly, and that the Raspberry Pi was able to read the new SD card, boot using the MBR, and bootstrap using the bootstrap partition, and begin booting off the OS-partition.  If you don't see the same result, validate firstly by examining the screen for any errors.  Most likely your cmdline.txt isn't linking to the OS-partition properly.  If you receive SD-card errors, first validate the structure of the SD-card is correct, and that you didn't eject/unmount before the changes were written completely to the card.

Monday, 23 December 2013

Monoprice 7-port USB Hub for Raspberry Pi [day 14 of 20-days-of-posts series]

The Monoprice 7-port USB hub is Raspberry Pu friendly.

The hub is powered by a 2amp power brick.  The power brick is fairly slim -- in a power bar, it would prevent another brick being plugged into the plugs next to it, but it does provide enough clearing to allow someone to plug a power cable into adjacent plugs.  The hub will provide enough power (1amp) to power the Pi.  Unlike other high-powered USB hubs that I have tried, the hub will provide greater than 0.5amp to device connected to it even though there is no host connected to it.  This is critical.  A lot of other hubs I have tried, they will provide high-power to a USB device connected to the hub only if there is an established host connection to the hub.  Therefore, if you try to connect a Pi to the hub, it is not able to provide enough power to the Pi to start it up because there is no host connected to the hub.  The Pi needs to be powered up before it will establish a host connection with the hub.

With the Monoprice 7-port USB hub, the hub will provide enough power the usb connections to power the Pi up even before the host connection is established.  This is witnessed by a red light on the hub, which indicates it is powered on.  When the Pi itself is powered on and started, blue lights will turn on the hub to indicate connections of those devices to the host have been established.



The hub also prevents backpowering over the USB host connect.  This allow for a switch to actually work.  Without this ability, the power switch would be futile as the Pi would become powered on automatically via the host connection between the Pi and hub when the hub gets powered on.

The hub will provide 5 USB side connections and 2 USB top connections.

The hub can be disassembled.  The plastic case is easily removed.


 The board could be integrated in your Raspberry Pi case design, as I have in my headless Pi server.




Overview of power switch options for the Raspberry Pi [day 13 of 20-days-of-posts series]

A power switch was omitted in the design of the Raspberry Pi to keep costs down.  There was no easy interface provided to add one either, but there are many different options.  I had previously tackled the original topic in a previous post, comparing a few options, including building your circuit.

Challenge:  The Raspberry Pi always remains powered-on as long as there is power coming in on the micro-USB power line.  A shutdown/halt/poweroff command will shutdown the OS and leave the system in a powered on but idle state.  The power consumption would be unchanged between idle and active on the Raspberry Pi.  Further, to turn the system back on, the USB cable needs to be unplugged or the power supply needs to be unplugged (reset).

Ideally we need....

  • something that powers the raspberry pi off when it is shutdown (power consumption becomes negligible / < 0.5 W) [POWER OFF]
  • something that can trigger a clean software shutdown [CLEAN SHUTDOWN]

Over the past few months since the  original topic / post, I've covered the following options:
I've felt it was time to do a head-to-head comparison of the five options that were discussed in the previous posts.

Assumptions:

  • all values are in USD; shipping costs and taxes are excluded throughout 
  • measurements are based on a scale of 1 - 5
Build Your Own Circuit USB Big Red Button illuminated /
rocker-style
by Mausberry Circuits
WeMo Switch by Belkin RemotePi Board
by MSL Digital Solutions
Product Page n/a link illuminated switch
rocker switch
generic USB switch
custom switch
WeMo RemotePI
Price varies based on parts
($ 5 - $ 40)
$ 1 - $ 7 $ 14 - $ 16 $ 50 $ 24 - $ 27
Integration  bulky setup plug into free USB port
3 jumper wires hooked upto GPIO
plug Pi USB power plug into locks onto GPIO
Easy of Hardware Setup  1 / 5
- soldering required
5 / 5
- plug-and-play
- solder-free

4 / 5
- risk of causing damage if you place the cables on the wrong pins
- solder-free

5 / 5
plugs in
5 / 5
- plugs in, screws on
- solder-free
Easy of Software Setup 

1 / 5
- requires writing your own app
2 / 5
requires installing apt-get packages, compiling and provided C code
/ 5
- run switch.sh install
- default script had issue causing crashing Pi, some modification needed to code
2 / 5
- requires phone app
- firmware and app buggy
4 / 5
- run irswitch.sh install
- program power button on remote
- setup lird.conf for remote
Reset Button
[hard reset]?
DEPENDS
if intercepts power source
NO iluminated switch NO
rocker switch YES
NO NO
Safe Shutdown? YES YES YES NO
(use some thought process around shutdowns)
YES
Power Consumption
[as measured by a kill-a-watt
negligible  negligible negligible 1.5 - 2.5 W
just as much power as the Pi!
negligible
Completely Powers off Pi? DEPENDS
if intercepts power source
NO YES YES YES
Powers Pi by GPIO, micro USB or USB (Pi rev B)n/a micro USB via micro USB micro USB or USB port (Pi rev B) GPIO via micro USB
Shutdown Scripts
device driverRaspBMC/Raspbian/Debian
OpenELEC
Arch
n/aOpenElec
RaspBMC
XBian
Major Selling Features - switches can be used for other purposes- switches can be used for other purposes - select models include reset switch
- rocker switch (left in on position) works with well WeMo to power on remotely
- power on Pi using different conditions
- remote power on / off / reboot
- includes IR receiver for XBMC
- only solution that can power on Pi via IR
Full Review previous post previous post previous post previous post previous post
My Sample Integration n/a n/a rocker switch
illuminated switch
n/a RemotePi

Illuminated and Rocker-style power switches for the Raspberry Pi


As previously discussed in in a post about power switch options for the Raspberry Pi, mausberrycircuits was identified as a source of several options.  Original a kickstarter campaign, the hobbiest sells various of his creations including power switches, custom switch PCB boards and car ignition boards all for the Raspberry Pi.   He will even work with your design requirements and alter the switch.



His power circuits is essentially a circuit board that is placed inline with the micro-USB power line, with two connections to the GPIO (1 input, 1 output).  A press of the button or a toggle of the switch takes the unit from off (complete power off for the raspberry pi) to on mode.  A shell script starts on bootup that passes a high/1 to the switch to instruct indicate the raspberry pi is on.  A low/0 signal passes from the switch to the raspberry pi to indicate the switch is neutral.  A toggle of the rocket switch to off or holding a press button switch for two seconds changes the output to high/1 which the polling script triggers a safe poweroff.  When the raspberry pi has finally fully shutdown, the GPIO goes from high/1 to low/0, which tells the switch the raspberry pi power can be cut safely.  The rocket-style switches also come with a reset button that can trigger a raspberry pi reset if it becomes frozen, etc -- something that normally would require to pull the power line.

The switch also detects software shutdowns invoked by the user (as the GPIO will toggle from high/1 to low/0, which the switch polls for).


Pros:

  • very small
  • may need some modification to your raspberry pi case
  • addresses the CLEAN SHUTDOWN and POWER OFF requirements fully.

Cons:

  • expensive but cheaper then any alternatives
  • everything fully assembled


I purchased a number of the switches from Mausberry Circuits.  The illuminated push button switch easily integrates into my lego design cases -- the added width is 1 lego block.

The illuminated switch integrated:

Here's what my case looked like before adding the switch:



I had to rip down the right-side wall to set it up.  But it is lego after all.  Time to integrate the switch into the case!



After:



The rocker-style switch integrated:


My original First Raspberry Pi Model B lego case revitalized [day 12 of 20-days-of-posts series]


My original lego case design case was previously discussed.  Since then, I've integrated an all-in-one LED, IR receiver and power switch board, plugged into the GPIO.  I decided to take this time to drastically improve on the original case design.


Intention: To be used for various purposes including as an XBMC media player,airplay server/client, a ASTC to wifi converter box, etc.  Need for both ethernet and wifi and access to a keyboard/trackball.


Equipment:
  • Raspberry Pi (model B -- memory: 512MB, 2 USB ports, ethernet)
  • RemotePi Board (previously reviewed)
  • class 10 SD card
  • micro USB (for power, plugged into TV <-> raspberry pi)
  • HDMI cable
Assumptions:
  • possible need for VIDEO port
  • possible need for AUDIO jack
  • no need for access to the i/o ports (camera port, GPIO pins, etc)
  • require a "window" for IR receiver
  • require a "window" for the power LED


Like with most of my lego projects, I don't provide full schematics and block lists.  My opinion is that if you have unused lego that you can use for a project like this, you make use of what you have, improvising as you go.

Front-side view

Before:


After:


A big transformation on the front side of the case.  The IR receiver is no longer snaked along to this view-point.  Therefore, it is no longer the front-side.

The IR window and onboard Pi LED window is replaced with a smaller transparent block that glows and presents better than the original.  The window door is replaced with a much shorter pair of "flag" doors, providing access to the VIDEO and AUDIO jack, keeping them "tucked away" when not in use and not negatively impacting the functionality of the case while in use.

The front of the unit no longer curves up, shortening the base of the unit by 1 lego block size. The height has been drastically reduced from s 4 +1/3rd lego blocks to 3 blocks without affecting any functionality. The bottom 1/3rd lego block size is now self-re-enforced grey layer.  The second 1/3rd lego block size black layer is gone, now that the base has better structure from a single layer.


Right-side view:

Before:

After:

I placed a white window block where the power switch's onboard LED is positioned, that gives the unit a nice glow when lit.  I placed an inset blue window piece for IR window.  The IR range provided by the window is adequate enough to get at least a 45 degree angle using the remote.  I moved up the blocks for the micro USB power port to line up with the new port.  I also added some support around the SD card as it was previously hanging out of the system.  It is now protected from being hit (and damaging the SD card port).


Back-side view:

Before:
After:


I had to get rid f the original HDMI top-swing door.  It required 2 + 2/3 lego blocks height.  With the shorter height, it was not possible to accommodate the door.  These "flag" doors are starting to become a favourite of mine, as they stay on better and they have a smaller footprint, adjust easier, and don't distract.  When not connected to a monitor/TV (for headless operation), the doors are swung down to prevent dust buildup.

Left-side view:

Before:


After:


The top-swing door over the ethernet port was shortened to accommodate the new height of the case. The door allows the port to be tucked away when not in use.  It sits perfectly flush to the unit, and with a change in the door swing mechanism the door doesn't become flimsy when open (easily falls off).

The LED windows have been eliminated since they are visible through the front-side view.

The unit is depicted with a wifi dongle and a wireless lenovo multimedia keyboard/trackpad dongle.


(this keyboard, which I owned for 1-2 years prior to owning the pi, but had yet found not a single purpose for it.  Now I find the keyboard a pure necessity )


Top view:

Before:



After:


The original base size was 13 by 10 blocks.  The new one is slightly smaller with a 13 by 9 blocks.  Had I implemented an illuminated switch instead of the RemotePi board, I would of had to increase the length from 13 to 14 as I had in previous cases.

A push-button power switch is accessible from the top of the unit.  Pressing down will either turn on the Raspberry Pi or safely shut it down (and power it off).

The GPIO access doors are gone.  Since we are using the GPIO for RemotePi board, there is no need for them.  If I ever receive my ordered Raspberry Pi camera, I may open up access to the camera port.

RemotePi Board power IR switch for Raspberry Pi [day 11 of 20-days-of-posts series]

A power switch was omitted in the design of the Raspberry Pi to keep costs down.  There was no easy interface provided to add one either, but there are many different options.  I had previously tackled the original topic in a previous post, comparing a few options, including building your circuit.

I had previously reviewed several different Raspberry Pi switches.  A new one came to my attention that I placed an order for.  It is the RemotePi Board by MSL Digital Solutions.



At its core, it promises the same functionality has the other board solutions that intercept the micro USB power connector on the Raspberry Pi, which is to control the power on/off state of the Pi through a switch and through software.  But instead of intercepting the power flow through the micro USB power connector, it controls the power through the GPIO.  Instead of connecting your power to the micro USB power connector on the Raspberry Pi, you connect it to this board.  You then either toggle the power state by pressing the black button on the top, or better, you can use a IR remote to toggle the power.

And there lies one of the key differentiators.  For application use-cases such as a media player where you need an IR receiver, this board accomplishes that purpose as well.  I discussed how you could construct your own IR receiver setup on the GPIO in a previous post, and also talked about HDMI CEC in the same post, but one of the issues that remains in either the case of adding an IR receiver or using your TV's built in HDMI CEC support (if it has it), is that you can't power on or off your Raspberry Pi using either your Pi or TV remote.  Your solution options were either to always leave the Raspberry Pi on, have it automatically turn on when your TV is on (either by a power bar or plugged into the USB service port on your TV) or manually turn it on using a hardware switch or plug when you want to use your Pi.

I don't always watch all my media content through the Raspberry Pi (such as when I play video games, watch TV channels etc), so I resorted to using the illuminated switch bundled with my IR receiver that allowed me to keep my Raspberry Pi off, when not in use, and turn it on manually by pressing the switch when I wanted to watch some Pi content.  There were a couple times I wanted to be able to use my Logitech Harmony remote to turn on the Pi.  One of the benefits of this switch implementation is that it will use the IR remote's power button to toggle the power to the Pi.  The IR receiver on the board will also work like any standard /dev/lirc device, meaning that it could replace the IR receiver I had setup on my Pi -- that it was completely compatible with XBMC.



The switch and IR receiver is contained on a single logic board.  It has a connector port that plugs directly into the GPIO.  This wasn't a concern for me, since on my XBMC Raspberry Pi units, I only use the GPIO for two purposes -- hooking up a power switch and hooking up a IR receiver.  The direct connection to the GPIO eliminated some wiring that I needed to contend with with the IR receiver and previous power switch.  The board also came with a screw with some watches and nuts so that it could be securely mounted directly onto the mount hole on the Raspberry Pi.  The first releases of the Raspberry Pis (the model B 256MB "rev 1") don't have this mount point but the board is still usable without the mount..

I decided to integrate the board with my model B bedroom TV Raspberry Pi case.  I had reviewed the lego case I had constructed for that project in a previous post.  I had still not integrated any power switch into this unit, so I was eager.

To keep inline with the pros and cons list I provided for the other switch mechanisms, here are the lists:

Pros:
  • very small
  • may need some modification to your raspberry pi case, but otherwise fits within the existing case (doesn't extend out from the board's footprint)
  • addresses the CLEAN SHUTDOWN and POWER OFF requirements fully
  • no issues with provided switch script (for other switches, I had problems and I had to make customizations to the scripts provided by other offerings)
  • fully integrated IR receiver that can be used to allow your IR remote to control XBMC
  • everything fully assembled

Cons:


I took apart my case's right wall to accommodate the new higher-oriented micro USB port.  I would be revamping the case completely now that I no longer needed to snake my IR receiver around to an opening on the front of the unit, I could now also drop down the height of the case due to the same reason and I would need to accommodate the hardware button to accommodate the manual switch.

The instructions provided were very simple.  After I applied the screw and plugged in the board, I connected the micro USB power to the board's port.  Immediately I saw the built in power LED flash green and red momentarily to indicate the unit had power.  I then press and held the power switch button down for 15 seconds, at which time the LED blinked between red and green continuously, indicating that it was ready to read the IR remote command for the power button.  I used the Logitech Harmony power button that had been setup for the WD TV remote profile that I had setup previously on the unit's previous IR receiver.  It really doesn't even have to be a power button -- it can be any unused button.  The blinking stopped and I could then press that button to turn on the unit.

When the IR power-assigned-button is pressed, the board's onboard LED starts blinking green, while the Raspberry Pi turns on.  Everything booted up as it would regularly.  I didn't have to make any changes to my lircd.conf profile.  I started using the unit as I normally would.



The blinking -- which is more of a "pulsing" -- for up-to-one minute on startup and shutdown give an indication that the command was received and also indicates that the unit won't respond to subsequent power on/off requests from IR during that period.  This prevents accidentally sending a second power on/off command to the unit while it works on the initial request.  It also prevents "repeating" if the IR remote sends the same commands multiple times.  .

If you are implementing this as a new IR implementation (not replacing an existing setup), you'd need to setup a remote and lircd.conf.  I discussed how to do this in a previous post.

I had no problem using the onboard IR receiver with all my Harmony remote commands or with the WD TV remote that I keep around as a backup to control the unit when my Harmony remote is lost in the room-somewhere or is charging.

To power off, I pressed the power button again.  The board passes on all the IR signals received to the Raspberry Pi, including the one assigned to the power button, but it will start triggering a shutdown when the power-assigned button command is received.  It does this by the irswitch.sh script that is installed as part of the setup.  It closely resembles the safe shutdown script (switch.sh) that I discussed using with the other power switches.  The board's LED flashes red while the board shuts down the Pi.  It continues to monitor the Raspberry Pi's shutdown for up to a minute.  When the Pi is safely complete it's shutdown, the power is cut off (so the Pi becomes powered off), and the onboard LED turns off.  You can then use either the manual power button on the board or again the IR remote's power-assigned button to turn the Raspberry Pi back on.



The onboard LED proved to be a great asset to this power switch.  I no longer had to position the front-face position in my original lego case:



I retweaked the right-side of the case to become the new front-end of the unit.

The before:



The after:



I placed a white window block where the onboard LED is positioned, that gives the unit a nice glow when lit.  I placed an inset blue window piece for IR window.  The IR range provided by the window is adequate enough to get at least a 45 degree angle using the remote.  I moved up the blocks for the micro USB power port to line up with the new port.  I also added some support around the SD card as it was previously hanging out of the system.  It is now protected from being hit (and damaging the SD card port).

A closer view:



I revamped the top of the case to integrate the power button as well:




I review all the changes I made to my Raspberry Pi lego case for this board in this follow-on post.  In general, it is very easy to integrate the board into most cases as it doesn't change the footprint size of the Raspberry Pi.  The only customizations that are needed are:

  1. hole on the top for the manual power switch,
  2. relocation of micro USB power source in a higher position and
  3. uncovering for IR and LED visibility.



Belkin WeMo Switch as a Raspberry Pi Power Switch [day 9 of 20-days-of-posts series]



Recently I purchased a Belkin WeMo Switch.  The switch makes a single electrical outlet become online by putting it on Wifi.  You can then use an iOS 6+ or Android 4+ app to toggle on/off the switch.  I didn't really see to much benefit of the app, as I already use Connected by TCP to control lighting around the home, providing me the ability to dim lights as well.

Of bigger importance to me was the IFTTT capability of the switch.  IFTTT, which stands for If This Then That, is an online service that lets you create recipes that can toggle the WeMo.    Because IFTTT is enabled for many other online services, you can tie the toggle on/off of the WeMo to other events, such as a gtalk or email message.  You could toggle the WeMo by the sending of a message to a IFTTT bot that contains a hash-tag that you assign to toggle your WeMo.  This makes it really easy to control a switch in your home from any device, not just your phone.  Likewise, IFTTT also has scheduled events as an ingredient, so you could use it to control what times your WeMo is on and off for.



There is a newer version, called Belkin WeMo Insight switch that has a much smaller footprint and also monitors and reports the power consumption of the device plugged in.  The Insight switch is about $10 more expensive.  It wasn't carried in any stores in Canada at the time of purchase (Home Depot, Canadian Tire, Future Shop / Best Buy, Amazon)

My particular interest in the Belkin WeMo Switch was as a Raspberry Pi power switch.  It makes a powerful switch for the following purposes:

  1. Serves purposes where something similar to as WOL (Wake on LAN) is needed.  I often use WOL on my systems, so remotely, I can connect to my home network and turn on computers as I need them, but issuing a WOL packet from the router to the PC.  For the Raspberry Pi, the Pi is always on as long as it has power supplied to it, therefore the USB-based ethernet switch doesn't feature the ability to turn the system on by WOL.  To do so, you would need to design and build your own power switch that could intercept the micro USB powered source and also reimplement the ethernet port by intercepting ethernet traffic capturing WOL packets and then controlling the power based on that.  There exists no ready-made logic board, so creating and implementing one would be impractical (and expensive).  With the WeMo, you can the toggle on power command straight to the switch, and anything connected to it will turn on.
  2. Scheduled on/off time.  If you need the system to be powered on during a certain time of the day (scheduled crontab job),  you can schedule the toggle on of the WeMo by a scheduler on  IFTTT.  Likewise, you can toggle it off at a different time.  Therefore, a scheduled crontab entry, I schedule my WeMo to be triggered on 5 minutes before the crontab entry is to run, and likewise, I schedule the WeMo to be triggered off 5 minutes after a matching crontab entry on the Raspberry Pi is scheduled to shutdown the system. Further, because there are three kinds of states you can use (toggle on, toggle off, toggle power state), if you toggle on the WeMo at a scheduled time, if it is already on, it won't be affected (as in, it won't be turned off by accident, unless you use the toggle power state as opposed to toggle on).
  3. Control your USB powered hub.  In my particular application, I'm powering the Pi using a power switch, which is plugged into a hub, where my USB devices are also plugged in (such as hard drive).  So, although I can schedule a shutdown on crontab which actually powers off the Pi with the addon power switch, the USB devices such as hard drive, remain powered on.  With the WeMo, I'm actually powering on/off the USB hub, so it would include automatically powering on/off the Pi itself.
  4. Remote hard-reset.  If (really more of a case of when) the Raspberry Pi becomes frozen or unresponsive where I'm not able to connect to it remotely to perform a reboot command, The WeMo allows me to either use my phone or IFTTT to toggle the power off/on.
Some conditions or other notes:
  • If you are strictly power off using the WeMo, you could corrupt the SD card or USB-based hard drive filesystem if you practice the habit of poweroff by cutting the power as opposed to safely shutting down prior with either a poweroff or shutdown now -h command.  In actuality, you could use a third party, such as Linux-capable router (which is my case), where if I need to perform a safe power down, I have the router issue a shutdown now -h over ssh to the Raspberry Pi, and then issue a #pi-off over email to IFTTT a minute later to actually power off the device.
  • If your Raspberry Pi starts up requiring root login to correct a disk issue, then you have no way around the issue other than to interact with the Raspberry Pi locally.  There is probably some way around this, some setting that lets you disable disk checks on startup, thus avoiding the prompt at startup for a root admin to log on to perform maintenance or CTRL-D to continue.  These prompts are not just tied to real disk corruption.  If I take my USB hard drive offline to sync it with another hard drive using another PC, if I write changes to it's supernode in the process, the next time I boot up on the Rasbperry Pi, it'll see the supernode has a timestamp newer than the system clock and thus refused to boot until a root user takes a course of action.  This nuance is for the fact the Raspberry Pi lacks a realtime clock, so on bootup, the present time will be the time at which the system was last on (stored to the SD card), so the fact the hard disk was updated or had changes to it with timestamps that are newer, it detects this as possible corruption-based issue.  Only after the system is booted up and on the network will the NTP set the time on the Pi to the current one.
  • You need an iOS 6+ or Android 4+ device even if  you intend to only control the WeMo via IFTTT.  The WeMO needs to be setup via the phone app.
The initial setup of the WeMo was fairly simple.  From what I read, the Android version of the app was created more recently and just came out of beta, and tends to have more bugs in it then the iOS version.  Therefore, I decided to dig my iPhone 3GS out of retirement for setting up this device, over the Android.  I plugged it in, then on my iPhone 3GS, I downloaded the WeMo app from the appstore.  As instructed by the app, you then need to change your Wifi access point on the phone to the one broadcasting from the WeMo.  Then at this point, the app will ask about the network setup of the WeMo, for which you provide the network key.  This was fairly simple.  But I did read online that a lot of users had problems at this point as their WeMo didn't accept network passwords with special characters (non-alphanumeric) such as spaces.  I'm not sure if this is resolved with a newer firmware, but if you have a network that uses one, you're out of luck with a out-of-box device until you get it onto a network it will accept.

As part of the setup, you provide it a name for the switch (assuming you may one day have multiples).  In my case, I just called it Raspberry Pi Server.  You can also assign it a user-created PNG graphic to depict the device image in the app.

After I got the device setup, I was prompted by the app to update the firmware on the WeMo as there was a newer one available.  This is where I began to quickly learn how buggy the firmware and app are.  I accepted the app to let the WeMo download the firmware.  At this point it instructs you that you can close the app, that the WeMo is downloading the firmware direct (indicated by flashing blue light) and will take about 10 mins to complete, at which time the WeMo will reboot and be ready for use.  I left the app open just the same, and went off to get a coffee.  When I got back I saw the WeMo was done the firmware upgrade, but instead of a steady blue light (indicating on) or no light at all (indicating off), I was presented with a blinking amber light.  It would seem this may have multiple meanings, but the initial one I found was that the device was not able to conenct to wifi or is still trying.  Checked the router and it confirmed the WeMo was not connected, having been connected and assigned an IP prior (since it had finished setup and had downloaded the new firmware).  I checked the phone app and it indicated the device was "firmware upgrading".  Unplugging it and plugging it back in proved futile.  I quickly learned of the restore procedure to try to trigger the device to restore to factory state.  So, went through the initial setup again, assigning the device a new name, giving it the network password etc.  This time at the completion of the setup, instead of letting me see the state of the switch in the app, it said the device was "firmware upgrading".  I had used a different name the second time, and it was the second named switch that it was in belief was firmware upgrading, whereas looking at the device, no said activity was underway.  Closed the app and started it again, and it was able to see the on/off state of the app correctly.

So, as you can see, both the app and the WeMo firmware are buggy, and I'll be more apprehensive on updating the firmware in the future.  Because it was freshly out of the box, I tend to take on more risky behaviour such as updating firmwares since I can just turn around and head back to the store to return the bricked device.  Had I updated in weeks or months following, I'd be at the mercy of the manufacturer RMA procedure.  

Setup was easier for IFTTT.  Activating the WeMo channel in IFTTT just involved providing it the  unique identifier number that the phone app provided so IFTTT could locate and use the WeMo.  I didn't have to open any firewall ports, etc.  Either the WeMo is pulling the requests or it is opening a port on the firewall itself.  I'll look into the details someday.  I'm interested in seeing what the packets look like going between IFTTT and the WeMo.

Pros:
  • IFTTT support
  • the latency is minimal; within 1-2 seconds of triggering a power toggle on the app or in IFTTT, the WeMo is toggled
  • this speaks more to IFTTT itself, but the time between emailed hash-tag emails to invoke the WeMo are processed usually around 5 seconds after the email request departs
  • survives power failures with settings preserved
Cons:
  • pricey (around $40 - $50)
  • firmware update process is buggy
  • requires the phone app for at least the initial setup
  • users report problems with network passwords with non alphanumeric characters
  • almost guaranteed to have problems with enterprise networks (such as ones that requires LEAP etc)
  • no surge protection; designed to fit outlets, not power-bar friendly, but it contains no surge protection and the huge footprint of the device causes hindrance plugging it into outlet surge protectors
  • unless your outlet plug sits flush with the surrounding wall, or extends out a bit, the overhanging of the switch will cause problems
  • causes havoc with powerbars; the footing is larger than power bricks, so even when a powerbar (or in my case APC UPS) has a "power brick outlet" to eliminate impact of a power brick on adjacent outlets, the footing still causes problems, barely allowing a two prong cable to clear (see picture of my setup)

[There is a newer version, called Belkin WeMo Insight switch that has a much smaller footprint and also monitors and reports the power consumption of the device plugged in.  The Insight switch is about $10 more expensive.]
  • network security issue; network details of the device are not transparent which is probably intentional to obscure security vulnerabilities 
  • it is essentially an embedded computer, so when you first plug it in (or turn a power bar on) it takes about 30-45 seconds for it to boot up (indicated by blue blinking LED) and another 30 seconds for the device to find and connect to the network (indicated by amber blinking LED)
  • consumes power (using a kill-a-watt reader, the device registers at 2 watts when idle and around 2.5 watts at bootup) -- the Raspberry Pi model B rev2 consumes about 2.5 watts, and the Raspberry Pi model A consumes about a constant 1.5 watts, so the WeMo consumes the same or more power than the Raspberry Pi.
Pros as a Raspberry Pi switch:
  • control the power switch remotely
  • lets you perform hard reboots remotely
  • control the power to the USB hub and all your Pi devices with a single switch
  • control the power to your Raspberry Pi using IFTTT, including implementing scheduled activities, activities based on other events
  • home automation necessity -- use in conjunction with motion sensors tied with IFTTT to aid in setting up home automation;  the WeMo switch is only one product available in the WeMo Home Automation category.
Cons as a Raspberry Pi switch:
  • no software shutdown support (need to software shutdown prior to avoid corruption of filesystem)
  • expensive

Saturday, 21 December 2013

Simplistic slim Raspberry Pi model A red lego case [day 8 of 20-days-of-posts series]

Intention: To be used as a small travel Raspberry pi that can be used with displays on-the-go (such as lapdocks)


Equipment:
  • Raspberry Pi (model A -- memory: 256MB, 1 USB port, no ethernet)
  • class 10 SD card (32GB)
Assumptions:
  • No need for the VIDEO port (going to use HDMI)
  • No need for AUDIO jack (going to use HDMI)
  • No need to access camera port, GPIO pins, etc


Like with most of my lego projects, I don't provide full schematics and block lists.  My opinion is that if you have unused lego that you can use for a project like this, you make use of what you have, improvising as you go.

This is the smallest Pi case that I could make, ideal for travelling.


Left-side view:




We have access to the USB port.  The Raspberry Pi LEDs are viewable through a window.

We can see the height of the case is exactly 2 + 1/3rd lego bricks high.  The width is 10 lego bricks.

Right-side view:



The SD card slot is accessible and the SD card sits flush to the case.  The micro USB power port is exposed for easy access.


Back-side view:


An opening is provided for eacy access to the HDMI port.

We can see the length of the case is 14 lego bricks in size.







Wednesday, 18 December 2013

Customizing your Raspberry Pi remote [day 7 of 20-days-of-posts series]

Yesterday I discussed how you could install an IR receiver on the Raspberry Pi so that you could use an IR remote to navigate XBMC.

Today I dig a little deeper into the configuration, settings and customization.

I assume your IR receiver is working (as described in the previous post).    We continue where we left off...


To create a configuration for a given remote, run the following:

  1. sudo /etc/init.d/lirc stop
  2. sudo irrecord -d /dev/lirc0 ~/lircd.conf
As part of generating lirc.conf, you'll be asked to enter a key name and then press that button on the remote so that it can read the IR signal and associate with that key.

To see a list of keynames, run irrecord --list-namespace .  Some very common ones are:

         KEY_HOME
         KEY_BACK   
         KEY_SELECT
         KEY_LEFT
         KEY_RIGHT
         KEY_UP    
         KEY_DOWN   
         KEY_REFRESH  
         KEY_FASTFORWARD     
         KEY_REWIND  
         KEY_PLAYPAUSE 
         KEY_INFO        

When prompted for a key name, you would enter something like KEY_HOME and then press the HOME key on the remote.  This would capture that input and the IR code associated with the key.  If you use an invalid key name or need to change it, you can do so by modifying the generated output (in this case,  ~/lirc.conf).

For a sample remote, I used a Western Digital TV (WD TV) player that I no longer use. and the generated output of that remote is as follows:
(download lircd.conf)
# Please make this file available to others
# by sending it to <lirc@bartelmus.de>
#
# this config file was automatically generated
# using lirc-0.9.0-pre1(default) on Sat Apr 13 23:25:54 2013
#
# contributed by
#
# brand:                       /home/pi/lircd.conf
# model no. of remote control:
# devices being controlled by this remote:
#
begin remote
  name  /home/pi/lircd.conf
  bits           16
  flags SPACE_ENC|CONST_LENGTH
  eps            30
  aeps          100
  header       8935  4503
  one           520  1709
  zero          520   606
  ptrail        524
  repeat       8935  2275
  pre_data_bits   16
  pre_data       0x219E
  gap          108035
  toggle_bit_mask 0x0
      begin codes
          KEY_BACK                 0xD827
          KEY_BOOKMARKS            0xF00F
          KEY_DOWN                 0x00FF
          KEY_ENTER                0x10EF
          KEY_FASTFORWARD          0x7887
          KEY_FAVORITES            0x08F7
#          KEY_FORWARD              0x7887
          KEY_HOME                 0x609F
          KEY_INFO                 0x58A7
          KEY_MENU                 0x58A7
          KEY_LEFT                 0xE01F
          KEY_NEXT                 0x807F
          KEY_PLAYPAUSE            0x50AF
          KEY_POWER                0x48B7
          KEY_PREVIOUS             0x40BF
          KEY_REWIND               0xF807
          KEY_RIGHT                0x906F
          KEY_STOP                 0x20DF
          KEY_UP                   0xA05F
      end codes
end remote
If you have a Logitech Harmony remote, life is even easier.  You can select almost any media player remote, push the settings to your Harmony remote, and then capture they keypresses like described in the above.  If you want to cheat, you could search for the remote setting for "WD TV" and then skip capturing the codes and just copy-and-paste the above lircd.conf as your own.  

If you didn't generate the lirc.conf in the correct location, or if you are copying it from a difference source, make sure you store it in /home/pi/ on your Raspberry Pi.

All you need to do now, is in Raspbmc Settings (under Programs), use the settings Enable Repeat Filter (enable/fill in dot), Enable GPIO TSOP IR Receiver (enable/fill in dot), GPIO IR Remote Profile select Custom (lircd.conf on pi's home folder).

Then either restart XBMC (you can kill -9 on the xbmc.bin process in a ssh session) or reboot the Pi, and once the Lirc service starts in XBMC, your remote should control XBMC.

We don't have to stop here.  We can further move onto some customization.

It might be handy, for instance, to associate a remote key to a function.  For example, there is no key set that would allow us to quickly access the Favourites Menu.  In actuality, we can associate almost any function in XBMC to a key on a remote (likewise can be done for keyboard, mice, and joysticks).

We can repurpose an existing key, such as KEY_HOME, which we will use for this example.  If you have a Harmony remote, you could create virtual keys fairly easy that would appear in the activity screen on the remote.  The "WD TV" device in Harmony actually contains a few such keys such as A, B and C.  You can look up any unusued key name in the keymap (running the irrecord --list-namespace that was ran earlier), and associate the IR signal to the key name and add it to your lircd.conf.  For simplicity, this example will simply repurpose the KEY_HOME.

On the Raspberry Pi, I will create a file /home/pi/.xbmc/userdata/Lircmap.xml .  I add the following entries to that file:
(download Lircmap.xml)

<lircmap>
 <remote device="devinput">    
<back>KEY_BACK</back>
<up>KEY_UP</up>
   <left>KEY_LEFT</left>
   <select>KEY_SELECT</select>    
<right>KEY_RIGHT</right>
   <down>KEY_DOWN</down>
   <stop>KEY_STOP</stop>
   <info>KEY_INFO</info>
   <skipminus>KEY_REWIND</skipminus>
   <play>KEY_PLAYPAUSE</play>
   <skipplus>KEY_FASTFORWARD</skipplus>
   <menu>KEY_HOME</menu>
 </remote>
</lircmap>
In  Lircmap.xml, I am associating my key names to functions in XBMC.  You can look up all the available function names from http://wiki.xbmc.org/index.php?title=keymap .  It appears they are case-insensitive (Play = play).  I can associate the keys to explicit functions.  Because you are using KEY_* names that are actually valid and common, these are mapped to their appropriate functions in XBMC by default.  Therefore, you could have stopped and not created this file, and still be able to use the keys to invoke common functions in XBMC.  You only have to create this file and start mapping keys once you have decided to reprogram their functions.  You can select any available function name (you cannot make up your own, but you can select an existing name and repurpose it).  We will select an unused <menu></menu> and associate the KEY_HOME to it as in <menu>KEY_HOME</menu>.

Finally, on the Raspberry Pi, I will create a file /home/pi/.xbmc/userdata/keymaps/remote.xml .  I add the following entries to that file:
(download remote.xml)


<keymap>
 <global>   
<remote>      
<menu>XBMC.ActivateWindow(Favourites)</menu>   
</remote> 
</global>
</keymap>
I invoke the XMBC.ActiveWindow function and pass it Favourites to open the favourites.xml in a Favourties menu.  There are a number of windows that can be opened to common function.  There are also a number of different functions that can be called.  Favourites does exist in XBMC (it is actually a Window ID type that automatically loads whatever is listed in favourites.xml).  There are also a bunch of different window IDs that you can do the same action on.  You could literally have a 400 key remote and still not have enough keys to satisfy all the functions and windows to call upon.

At this point, with the menu defined to the KEY_HOME in the Lircmap.xml and the menu defined with our custom action to open the Favourites Window in  remote.xml, we can either restart XBMC (you can kill -9 on the xbmc.bin process in a ssh session) or reboot the Pi, and once the Lirc service starts in XBMC, your custom key should perform the action of opening the Favourites menu.

The last time I have is troubleshooting.  If a key doesn't appear to be performing correctly or if you don't believe you've mapped it correctly, while in XBMC on the Raspberry Pi, ssh into the system and run irw. When you press keys on your remote to XBMC, the actions and key names invoked should appear in the ssh session.  This will quickly help identify the key name associated with the key.  If you press a key and it doesn't appear in the session, it means you haven't mapped it in the lircd.conf.