Friday, January 18, 2008

Shell Script to Reorganize a Mirror to Match a Newer Mirror

This script has a very specific purpose, but you've probably had a chance where it could have come in handy. The idea is, if there are two mirrors of a bunch of files, and you reorganize (more around and/or rename) files on one mirror, then when you go to RSYNC the other mirror, it thinks the files that were only moved were added and deleted. 

To use this script, you would first move the files on one mirror, and generate an MD5 sum file, as in:
$ find ./ -type f -exec md5sum {} \; | tee checksums.md5

Then, copy this small file to the root of the other mirror, and invoke the script with the name of the checksums file:
$ md5sum-reorg.sh checksums.md5

The script will process every file under the working directory and attempt to correct its path so that it matches a file in the new 'checksums.md5'. Files not found in the checksums file are left alone. Files already in place are left alone (obviously), without even calculating their md5sum.

Script follows:


#!/bin/bash
#
# This file takes a checksum file (output from md5sum utility)
# and attempts to reorganize the files in the directory to
# match the listing in the md5 file.
#
# Files not found in the md5 input are left alone.
# Files already in the right place are left alone.
# Other files have their checksums computed and, if they are found
# in the md5 input, they are moved to the appropriate location.
#
# WARNING: It confuses duplicate files!!!
#

if [ $# -lt 1 ];
then
echo "Usage: $0 [checksums file]";
exit;
fi

declare -a SUMS
declare -a NEWPATHS

exec 10<$1
let count=0

echo "Parsing checksums and paths from input file...";

while read LINE <&10; do
SUM=`echo "$LINE" | cut -d' ' -f1`;
NEWPATH=`echo "$LINE" | cut -d' ' -f1 --complement | cut -d' ' -f1 --complement`;
SUMS[$count]=$SUM;
NEWPATHS[$count]=$NEWPATH;
((count++));
done
# close file
exec 10>&-

echo "Compiling list of files that need to be checked...";

TMPFILE=`mktemp`;
find ./ -type f -printf "%p\n" > $TMPFILE;

exec 10<$TMPFILE
while read OLDFILE <&10; do
echo "Trying to find new path for $OLDFILE";

SKIP=0;
let count=0;
while [ $count -lt ${#NEWPATHS[@]} ] ; do
if [ "${NEWPATHS[$count]}" == "$OLDFILE" ]; then
echo "File already exists at '${NEWPATHS[$count]}'";
SKIP=1;
break;
fi
((count++));
done

if [ $SKIP -eq 1 ]; then
continue; #skip the rest of this iteration
fi


echo "Computing checksum of $OLDFILE";
OLDSUM=`md5sum "$OLDFILE" | cut -d' ' -f1`;

# iterate over the pair of arrays until we might find a matching sum
let count=0;
while [ "$count" -lt ${#SUMS[@]} ]; do
SUM=${SUMS[$count]};
NEWPATH=${NEWPATHS[$count]};

if [ "$SUM" == "$OLDSUM" ];
then
if [ "$OLDFILE" != "$NEWPATH" ] ;
then
NEWPARENT=`dirname "$NEWPATH"`;
if [ ! -d "$NEWPARENT" -a "$NEWPARENT" != "." ];
then
echo "Making directory $NEWPARENT";
mkdir "-p" "$NEWPARENT";
fi
echo "Moving $OLDFILE to $NEWPATH";
mv "$OLDFILE" "$NEWPATH";
else
echo "Path hasn't changed.";
fi
break;
fi
((count++));
done

done

exec 10>&-

exit



In case it's not clear, this is offered without any warranty or guarantee whatsoever.

Friday, January 11, 2008

Scripts for Moving Large Files to DVD (GNU+Linux environment)

Often, we have tons of files (videos, ISO's, software packages, etc.) that we're done with but don't want to throw away. I have written a few scripts to pack a directory of these kinds of files up into volumes (without any kind of compression) so that they can be written to DVD. Each volume should have an MD5 sum file generated which provides both a directory for that volume (since you can keep a copy locally and search using grep) and a means to verify its integrity.



The first script attempts to "pack" files at the current directory level (it's non-recursive) into volumes of a specified size. This is really the only part of this post that warrants a real script since it's a nested loop. Note that really small files will always end up in the extra space on the first volume, so you may want to move them first.




#!/bin/sh
#
# Script takes files (or directories) in the current working directory
# and moves them to subdirectories for writing out to discs
#
# This allows collections of relatively same-sized files or directories
# of files to be packed into volumes for storage on optical media.
#
# Modified to output a shell script instead of making any changes
# Disk capacity can now be entered

# Defaults
discSize="0";
discDefaultSize="4380000";
discInitNumDef="0";
discInitNum="0";
scriptPathDef="pack.sh";
diskPath="disks";

echo -n "Enter the volume number at which to start [$discInitNumDef]: ";
read discNumOffset;

if [ "$discNumOffset" == "" ] ;
then
discNumOffset=$discInitNumDef;
fi
echo $discNumOffset;

echo -n "Enter the maximum capacity of the media [$discDefaultSize]: ";
read discMaxSize;

if [ "$discMaxSize" == "" ] ;
then
discMaxSize=$discDefaultSize;
fi
echo $discMaxSize;

echo -n "A shell script will be output, move files now? [y/N]";
read moveFiles;

if [ "$moveFiles" == "" ];
then
moveFiles="N";
echo "Not going to move files.";
fi

echo -n "Enter the path to save the shell script [$scriptPathDef]: ";
read $scriptPath;

if [ "$scriptPath" == "" ] ;
then
scriptPath=$scriptPathDef;
fi

echo "Going to write shell script to '$scriptPath'.";

# Declare disk size array
diskSizes[0]=0;
arraySize=1;

echo "#!/bin/sh" > $scriptPath;

if [ ! -d "$diskPath" ];
then
echo "mkdir \"$diskPath\";" >> $scriptPath;
fi

if [ ! -d "$diskPath/`expr $discNum + $discNumOffSet`" ] ;
then
echo "mkdir \"$diskPath/`expr $discInitNum + $discNumOffset`\";" >> $scriptPath;
fi

for file in * ;
do

if [ "$file" != "$diskPath" -a "$file" != "$scriptPath" ] ;
then
echo "$file";

discNum=$discInitNum;

newSize=`du -s "$file" | cut -f1`;
#discSize=`du -s todisk/$discNum/ | cut -f1`;
#discSize=`expr $diskSizes[$discNum] + $newSize`;
discSize=${diskSizes[$discNum]};

echo "newSize = $newSize, discSize = $discSize";

if [ $newSize -gt $discMaxSize ] ;
then
echo "$file is larger than the disc size, skipping it.";
else
while [ `expr $discSize + $newSize` -gt $discMaxSize ]
do
echo "Won't fit in $discNum + $discNumOffset: $discSize + $newSize > $discMaxSize";

discNum=`expr $discNum + 1`;

if [ $discNum -ge $arraySize ] ;
then
#diskSizes[$diskNum]=0;
diskSizes=( ${diskSizes[@]} 0 );
arraySize=`expr $arraySize + 1`;

if [ ! -d "$diskPath/`expr $discNum + $discNumOffset`" ];
then
echo "mkdir \"$diskPath/`expr $discNum + $discNumOffset`\";" >> $scriptPath;
fi


fi

discSize=${diskSizes[$discNum]};
done

echo "Going to move $file into $discNum to make $discSize kb `expr $discSize + $newSize`";

echo "mv \"$file\" \"$diskPath/`expr $discNum + $discNumOffset`/\";" >> $scriptPath;

# Update disc size entry
diskSizes[$discNum]=`expr $discSize + $newSize`;

fi

fi

done

echo "Disk sizes:";

for DISC in ${diskSizes[@]}
do
echo "$DISC kb";
done

exit;


The next, albeit more simple script creates checksum files (for later use with md5sum -c ...) in each volume and provides the option to save a copy of the checksum file to another location.




#!/bin/sh
#
# Create checksum files for disk volumes generated by 'disk-pack'.
# These files allow the fidelity of the optical media to be
# evaluated, and allow the contents of the disk to be catalogued.
#
# This file should not change any files; only add new files.
#

CATDIRDEF="`pwd`";
echo -n "Path to save a duplicate of the MD5 checksums [$CATDIRDEF]: ";
read CATDIR;

if [ "$CATDIR" == "" ];
then
CATDIR=$CATDIRDEF;
fi

echo "Saving duplicate checksums in '$CATDIR'";

if [ ! -d "$CATDIR" ];
then
echo "Directory doesn't exist.";
exit;
fi

PREFIXDEF="disk";
echo -n "Prefix to use in checksum file names [$PREFIXDEF]: ";
read PREFIX;

if [ "$PREFIX" == "" ];
then
PREFIX=PREFIXDEF;
fi
echo "Using prefix '$PREFIX'.";

for DISK in [0-9]* ;
do

if [ "$DISK" != "." -a "$DISK" != ".." ]
then
echo "Processing volume $DISK";
cd $DISK;
find . -type f -exec md5sum {} \; | tee ../tempsums.md5;
cd ..;

if [ -e "$CATDIR/$PREFIX$DISK.md5" ];
then
echo "WARNING: Catalog file already exists, using alternate name.";
NUM="0";
while [ -e ""$CATDIR/$PREFIX$DISK-$NUM.md5 ]; do
NUM=`expr $NUM + 1`;
done
cp tempsums.md5 $CATDIR/$PREFIX$DISK-$NUM.md5;
else
cp tempsums.md5 $CATDIR/$PREFIX$DISK.md5;
fi

if [ -e "$DISK/$PREFIX$DISK.md5" ];
then
echo "WARNING: File $DISK/$PREFIX$DISK.md5 already exists, using alternate name.";
NUM="0";
while [ -e $DISK/$PREFIX$DISK-$NUM.md5 ]; do
NUM=`expr $NUM + 1`;
done
mv tempsums.md5 $DISK/$PREFIX$DISK-$NUM.md5;
else
mv tempsums.md5 $DISK/$PREFIX$DISK.md5;
fi
fi
done


Finally, you're ready to put these volumes out to optical media (since you've minimized internal fragmentation, captured a catalog of the files, and took an extra step to preserve integrity). You can do so using your favorite method, but when there are many volumes (like more than three) I prefer to take the following steps.



The following command, if you have genisoimage will create a .iso file for the directory '40' and it will have the volume name "Volume40" when you mount it.


genisoimage -o volume40.iso -J -r -V Volume40 40/


After you have a .iso file, you're almost ready to burn. Always, always, always mount the ISO image (mount -o loop -t iso9660 volume40.iso isotest/), enter it and check some of the MD5 sums to make sure you have a good .iso file! You'll have to check the man page for genisoimage and make sure you're providing the command-line options correctly if the files in the ISO seem corrupted.



If you're familiar with cdrecord, it is now provided by wodim. You need to be root. The command looks like:

wodim -v -eject speed=8 dev='/dev/scd0' volume40.iso


Then, before I delete anything, I always insert the CD, preferably into another optical drive, and run md5sum -c volume40.md5. Now you know you have an exact copy, you can put it in a case and delete the original. Note I'm assuming that if the disc fidelity decays that the files can be found again from the Internet--make sure you have even more redundancy if these are your personal files!

New Split Directory Script

Follow-up to: "Making directory traversals more efficient"

Back at the beginning, I posted a lengthy script that would split up a congested directory alphabetically. Recently, I needed it again, but needed it to be smarter, so I re-wrote it. Also, I figured out how to insert code into Blogger. Enjoy.




#!/bin/sh
#
# by Ryan Helinski, January 2008
#
# This is the second revision of a script that should be used
# when there are too many files or directories at a single level
# on the file system.
#
# It now recognizes the word, "the", and that the name should
# be alphabetized by the words following.
#
# A script is output so the changes can be reviewed before
# any are made.
#
# The script should add to existing bin directories if they
# already exist.
#
# A further improvement would be to allow the split to be
# multi-level.

BINS=(0-9 a b c d e f g h i j k l m n o p q r s t u v w x y z);
BIN_EXPS=(0-9 Aa Bb Cc Dd Ee Ff Gg Hh Ii Jj Kk Ll Mm Nn Oo Pp Qq Rr Ss Tt Uu Vv Ww Xx Yy Zz);

SCRIPT_FILE=".script.sh";

echo "#!/bin/sh" > $SCRIPT_FILE;

for BIN in ${BINS[*]};
do
if [ -d $BIN ];
then
echo "mv $BIN .$BIN" >> $SCRIPT_FILE;
else
echo "mkdir .$BIN" >> $SCRIPT_FILE;
fi
done

INDEX="0";
while [ "$INDEX" -lt "${#BINS[*]}" ];
do
echo "mv [Tt][Hh][Ee]\ [${BIN_EXPS[$INDEX]}]* .${BINS[$INDEX]}/" >> $SCRIPT_FILE;
INDEX=`expr $INDEX + 1`;
done

INDEX="0";
while [ "$INDEX" -lt "${#BINS[*]}" ];
do
echo "mv [${BIN_EXPS[$INDEX]}]* .${BINS[$INDEX]}/" >> $SCRIPT_FILE;
INDEX=`expr $INDEX + 1`;
done

for BIN in ${BINS[*]};
do
echo "mv .$BIN $BIN" >> $SCRIPT_FILE;
done

ANSWER="";
while [ "$ANSWER" != "yes" -a "$ANSWER" != "no" ];
do
echo "Script written to \"$SCRIPT_FILE\", execute now? (yes, no)";
read ANSWER;
done

if [ "$ANSWER" == "yes" ];
then
sh $SCRIPT_FILE;

ANSWER="";
while [ "$ANSWER" != "yes" -a "$ANSWER" != "no" ];
do
echo "Delete script file? (yes, no)";
read ANSWER;
done

if [ "$ANSWER" == "yes" ];
then
rm "$SCRIPT_FILE";
fi
fi

exit;

Tuesday, December 04, 2007

Make OGG not MP3

In reference to recent news, MP3 is still gaining momentum, as Wal-Mart is replacing their Windows Media Audio (WMA) files with MP3. In my humble opinion, MP3 is still better than WMA because it is so well understood (coders, decoders, support, household name, etc.) and WMA is really just a way for Microsoft to get a piece of the Fraunhofer pie. However, as long as MP3 is really "gaining momentum", then we need to collectively do something about it...

Personally, I've made the following pledges and hope they inspire someone:
  1. I will not distribute MP3
    I deal with a lot of original content, and after mix-down there's a choice--how to encode it to let someone hear it over the Internet? I will always choose FLAC or Ogg Vorbis, and refuse to send an MP3.
  2. I will maintain my personal collection in Ogg Vorbis
    When I buy a new CD, the first thing I do (usually) is run it through GNOME Sound Juicer (which supports OGG and FLAC by default) and create Ogg Vorbis files so I can load it onto music player (software) or portable media player (hardware), and to protect the data from being damaged by wear on the CD. This is the cheif method that OGG could become ubiquitous. Transcoding MP3 to OGG is lossy (it's much better to start from the original sampling), and any audiophile would tell you it's not worth it. Therefor, the most important source of OGG files is at the source (audio CD, FLAC, etc.), and we can become less dependent on MP3 by replacing MP3 files with newly-encoded OGG files.
  3. I will not buy a portable media player that does not support free codecs like Ogg Vorbis
    Okay, I still want to be able to listen to MP3, but in order to support pledge #2, I need my portable media device to support OGG out of the box. I personally have a COWON (iAudio) T2, but there are many other options from abroad.
  4. I prefer Ogg Vorbis Internet radio over other formats
    Hey, if OGG has the same fidelity at a lower bandwidth (you'll note the rates on Internet streams have a lower average), then we're saving the host bandwidth by preferring an Ogg Vorbis stream. Also, since Internet radio is struggling with royalties, why don't they save themselves money by dropping their MP3 streams and providing only Ogg Vorbis streams? I feel that most Internet radio listeners would not mind having to download an additional codec (if they even need to) to make the switch.
These are reasonable commitments to make, and the second big corporations catch on, we'll start to see MP3 dwindle away. Ogg Vorbis will have to make a statistical win (what is the probability of an audio file being an OGG?), and a compatibility win (what is the probability I can play this OGG?) in order to acheive this.

Note that DRM is not even in my vocabulary--it seems like the only "solution" to DRM is to avoid it at all costs. This business of limiting where, when and who can listen to a file (that someone has paid for, mind you) is nonsense. This is exactly the reason we dropped vinyl albums and magnetic tapes for compact discs--so we could hear the same thing again whenever and wherever we want.

Tuesday, November 06, 2007

Finally, Gmail offers IMAP

Previously Google claimed that IMAP would be too difficult to implement given their unconventional e-mail organization scheme (all e-mails basically in one folder). Now, they've finally opened up IMAP servers which allows much greater control than POP 3 previously did. For instance, one should be able to now import old e-mails into Gmail so that now all your mail is searcheable from one place!

Thursday, September 20, 2007

GNU Screen -- The best thing since VNC?

I have recently found myself in a bit of a blunder. I found myself opening a VNC server (with vncserver) and then connecting to it just to open a bunch of xterm's, and this seemed wasteful to download pictures of a text-mode terminal. I also SSH in and run long-term tasks and want to disconnect--but don't want to use nohup because I might want to re-gain control of the program or just see in real-time what the output is.

Then I remembered I read the description of a software some time ago in pirut, and thought it was a great idea. This software, as I remember it, was much like what I've just found here, but it seems like this project is defunct. I know there was something which was its own daemon and allowed persistent sessions, but...

After a lot of Googling, I finally came accross GNU Screen. I find this software awesome! Basically, it's like a window manager for your Secure Shell, allowing multiple new shells to be opened and switched between, "screen splitting" so you can see two screens at once, persistence of your tasks--which was exactly what I was looking for, and other features like sharing the session between users. Now I can have my multiple terminals running on the remote machine and use them effectively and more efficiently than via VNC.

The Wikipedia article links to many good tutorials in its references section. I recommend you try a few of them, especially this one, but if you're like me--you need to know right away:

  • install: yum install screen

  • run: screen

  • disconnect: CTRL+a d

  • reconnect: screen -r -d



Disclaimer: Yes, VNC is newer than Screen. No, Screen is not convenient when you need to use GUI's since even if you get it to work, it's forwarding who X windows, which can be much too slow if you're connecting over WAN. VNC is definitely the way to go if you have GUI programs you want to use in conjunction with text-mode.

Happy screening!

Monday, September 03, 2007

Jamendo

Jamendo is an excellent program which allows artists to release musical works into the public domain under various formats. With plugins for programs like Rhythmbox, you can use the service as an Internet Radio, and if you like something you can visit the artist's site on Jamendo or get the whole album on BitTorrent. Recordings are uploaded in WAV for FLAC, and are distributed in OGG and MP3.

If you are an artist with content that you feel would should be in the public domain, sharing your original recordings is easy. More importantly, you can get feedback on your recordings from the Jamendo community, which can be exciting because all the opinions (although sometimes misguided) are impartial--which is more than you can expect of your friends :) .

Saturday, September 01, 2007

SourceForge.net User Network

Anyone can join SourceForge.net, even if you don't have a project to share. Many projects need testers, developers, documentation writers, and translators (and more). There's a long list of projects which have advertised they need assistance (http://sourceforge.net/people/). It's a great way to help out the SF.net community and gain coding experience both by examining code and by extending/adding new code.

Thursday, August 30, 2007

Configure OpenSSH to automatically authenticate

Sometimes entering your pass-phrase to gain SSH access can get redundant, or you may want an automated script to be able to authenticate as you (as described at http://sial.org/howto/rsync/).

I've been trying to do this for some time now--apparently if you read the man pages carefully enough you can figure this out. I thought I'd need a more advanced SSH client, but OpenSSH already has everything you need--the ssh-keygen program is key. Following is a brief walk-through of how to configure connection from client to server for SSH. Replace the words client and server as appropriate.

client$ ssh-keygen -t rsa


It will ask where to save, you want the default since this is where ssh will look. It will ask for a pass-phrase, and since we're trying to get around having to enter a pass-phrase, we don't want to protect our authentication, so just hit enter twice. Then it will give you a fingerprint and put files in your ~/.ssh directory.

Copy the ~/.ssh/id_rsa.pub to the server machine taking care not to overwrite the same file there:

client$ scp ~/.ssh/id_rsa.pub user@server.address:.ssh/client.pub


Now SSH to the server and add the public key to the authorized keys file like so:

server$ cd ~/.ssh
server$ cat client.pub >> authorized_keys
server$ rm client.pub


The SSH server won't let you use the key unless the file is secured. That is, the keys should only be readable by you.

server$ ls -l authorized_keys
-rw-rw-r-- 1 user users authorized_keys
server$ chmod og-rw authorized_keys


Now we should be able to open an SSH session simply by:

client$ ssh user@server.address


where you can omit the 'user@' part if the user names are the same on the local and remote machines.

Finally, note that doing all this means if you leave your machine open, an intruder has more doors they can open! This is why you should always lock and/or time-out your screen. If the key has no passphrase, then if someone copies it, they can gain access to the machine you opened with this procedure. Therefore, you should restrict access to your machine by configuring /etc/hosts.allow and /etc/hosts.deny. If you're concerned, don't let the passphrase for the key be null (use a passphrase). Taking these steps can help protect your key.

Thursday, August 16, 2007

Cost Review for Luxeon LED Headlight

To justify building on myself, I had to do a cost analysis.

Purchased:

4x D-cell Batteries ($5)
1x LED Dynamics BoostPuck ($35)
4x Lumileds Luxeon I Star/O ($25)

Subtotal: $65

Spare parts:
1x 270uF capacitor
1x 24-gauge (AWG) lead wire
1x Pentium3 Heat Sink
1x Mounting bracket
1x Rocker switch
2x 2 D-cell Battery Holder
1x 18-gauge (AWG) lead wire

Note that comparable systems are water-resistant and include a rechargeable battery system, but can cost from $120 up to $300.

Rebuild of Luxeon I Bicycle Headlight

This is a practical comparison between two light sources: an old 2-C cell halogen headlight and a single Luxeon I Star (with optics), both driven at the proper power. This is an image with no special adjustments and the sources about 5 feet away. It is easy to see that the Luxeon I has both more flux (total amount of light) and better throw (maximum intensity of beam). Note that halogen bulbs are known to be more efficient than traditional vacuum bulbs, see Lighting efficacy for more. According to my calculations, the power delivered to the halogen bulb is about 1.5 Watts, and the power to the Luxeon I (obviously) is 1 Watt. Note the spectrum of light output, and how this would make riding safer. This comparison allows the efficiency of the LED to really "shine".

Note that my power supply (limited to 1 amp) may not have been able to provide enough current to drive the Halogen bulb to the same power as the 2 C-cells, so the halogen light may get brighter with actual batteries. However, the power measurements quoted are absolutely correct and (together with the comparison picture) still illustrate the point of efficiency. Also note that only one Luxeon I (1-watt) is switched on in the comparison picture, whereas four are used in my headlight assembly.

The LED Dynamics BoostPuck 350mA current regulator came today. The model with lead wires attached was not available, so I had to solder on wires. It really is small as they say; even smaller than my rocker switch. I left the extra pins (reference voltage, and dim) not connected.


Using my power supply, I verified all the parts and connections were OK. The meter pictured is showing volts across the input power pins of the BoostPuck (out of frame). The system is was actually pulling down the voltage on my 1-amp-maximum power supply set at 6.0V by 200mV. You can see that the LED's are fully illuminated, which requires at least 12 Volts in their wiring configuration...


I soldered everything together as I mentioned I would in my last post (in series). I included a 270uF capacitor. The only problem with the BoostPuck is that it's a sealed unit and has no way to mount it to anything, unless you use the pins to anchor it (which I don't). It's not heavy, so I didn't think it's all that important. Using industrial hot glue, I fixed it to the rocker switch, and the capacitor to it as well. I expect the hot glue not to hold for long, especially if things heat up. I'll use some epoxy if all goes well--the hot glue comes off easily, epoxy won't.

The light output looks about right. It might be a little dimmer than the unregulated circuit, but it's worth the gains in battery efficiency/power delivery. The BoostPuck is producing over 12VDC across the four LED's in series, which is about what I expected. I haven't actually checked, but I'm assuming that the diode current is 350mA. I didn't make measurements of the current drawn from the batteries because of the AC components.


The light beam itself is continuous (as opposed to strobed); waving hands in front of the beam doesn't reveal individual light pulses as with other charge-pumping lights I've encountered. Also, the intensity differences between the new and old LED's is gone as I expected. The newer LED's needed a higher voltage than the older LED's to produce the same amount of light, and fixing the current at 350mA equalized the light intensity.

For clarity, below is a crude circuit diagram including all the parts.

Tuesday, August 14, 2007

Luxeon LED headlight assembly


Have an old processor heat sink laying around? This Pentium 3 heatsink is the perfect size for four Luxeon I Star/O assemblies (LumiLEDs Product# LXHL-NWE8). Luxeon light sources need very good heat dissipation, and this might be over-doing it, but why not prolong the life of the light sources?

I wanted to get around paying up to $300 for a battery-powered bicycle headlamp, so I decided to meet or exceed the expectations with available parts.

I initially bought only two of these Luxeon Stars (with optics) over a year ago. I didn't have a good way to drive them other than my Elenco Precision (TM) power supply and alkaline batteries, both of which are voltage sources. I tried using two D cell alkaline batteries, this provided 3.0V which is less than the typical 3.4V, and not didn't force enough current to for the LED's to be all the way on. I also didn't have a good mounting bracket, or a good way to mount the batteries to the bicycle frame.


Recently, using the mounting bracket from and old mechanical speedometer and zip ties, I was able to make an excellent mount. This stops the lights from changing pitch (very important for this application) or breaking free. I connected them all in parallel to try to give them all 3.0V from the two D cells.

Lesson learned: Don't solder when the device is a metal core PCB and it's sitting on a heat sink with silicon paste in between! Leave these PCB's on an insulator while soldering.


I noted that they were only drawing around 800mA, nowhere near 1.4A (4x350mA). I decided to increase my power supply voltage potential, but this meant there needs to be another component in series with the light sources to allow the excess voltage to be dissipated. In the application notes from LumiLEDs, they recommend using a 6V power supply and a 10 Ohm resistor for a Luxeon I. I added another battery pack to the frame to get 6.3V, but I decided to use 0.9V rectifying diodes (3A max) rather than four resistors (one in series with each supply) which would require desoldering. This achieved 1.6A with one diode in series and 1.1A with two diodes in series. I stuck with the two diodes in series to stay on the safe side. The diodes get rather hot very quickly since they're dissipating so much power. This is a major problem, by my measurements -- 45% of the power was being dissipated in the diodes themselves, delivering only 55% of the power from the batteries to the light sources. Another reason that a passive approach (linear mode voltage regulation) is bad for alkaline battery applications is that the higher the power delivery, the more the batteries self heat and increase internal resistance. In other words, Alkaline's are less efficient when discharged quickly. It is a common trend that batteries are more efficient with intermittent loading for reasons related to battery theory. For much more, see the IEEE paper Battery­Driven System Design: A New Frontier in Low Power Design, by Kanishka Lahiri, Anand Raghunathan, Sujit Dey, and Debashis Panigrahi.

Lesson learned: The voltage drop across an LED is related to the energy released in each photon--relating to the wavelength of the light emitted. (Note that this is the P-N junction voltage drop, and differs from the external voltage drop and light spectrum is also highly dependent upon construction materials). The current through the LED corresponds to the number of photons emitted--relating to the intensity of light emitted. These brief rules of thumb really help in understanding how to apply high-power LED's.

Lesson learned: Luxeon LED's are constant-current devices, so to get them to the proper luminous intensity and power consumption, they need to be driven at the proper current amperage. For Luxeon I's this is 350mA, for Luxeon III's this is 700mA, etc. This point remained subtle to me because I figured I could always just find a voltage potential which would result in the proper current being drawn. The problem is that LumiLEDs has a tighter manufacturer tolerance of 350mA operating conditions than the forward voltage (Vf) which is loosely maintained. This means each light source will require a slightly different Vf to draw 350mA and use run at the full 1 Watt. The most robust solution is a constant current source which can be used to drive multiple light source in series. This also allows the supply voltage to fluctuate (eg: a draining battery) and not affect the luminous intensity as it would without a regulator.

Lesson learned: A common optimization for alkaline battery-powered applications is to use a charge-pumping power regulator. These are capable of producing voltages higher than their input voltage (12VDC from 6VDC for instance) by intermittently presenting a larger load and driving an oscillating circuit. The typical result is luminous intensity remaining mostly flat until the battery is mostly depleted. Just connecting a 12VDC battery supply would result in an exponentially decaying luminous intensity.

These conclusions lead me to replace my diode-dissipating circuit with a switch-mode power supply including a boost circuit. Because of the scarce availability of through-hole mounting switch-mode power supplies and the necessity for a PCB, I was very happy to find products from LED Dynamics including the BoostPuck. Their Application Figure 3 in their datasheet is my exact application. The regulators are unfortunately around $34, but it's worth the efficiency of a switch-mode power supply, the optimized battery utilization, and proper driving (constant current of 350mA) of the light sources to get the most light without risking burning out the LED.

When the unit arrives, I'll removed the hot glue (to keep the parts clean) and connect the light sources in series and connect the BoostPuck to the ligth sources after the rocker switch. As per the application notes, I'll need to include a capacitor since my batteries are a few feet away. More as soon as the part comes in.

Friday, August 03, 2007

1979 Free Spirit Ten Speed


Once I started riding this old Free Spirit ten-speed, I was hooked. Most of my riding is on a paved recreational trail, so the thin tires aren't a hazard and the bike is a lot more efficient than a Mountain Bike on those conditions.


The bicycle came from Sears & Roebuck circa 1979. I decided that even if I buy a new road bike, that I wanted to keep the Free Spirit around since it was in such good condition compared to a few much younger bikes I have seen. The parts are old (Shimano) parts, but most of the following procedures still apply to most bicycles.

The first problem was that the wheels needed to be "trued" very badly, the crank was loose, it had lots of grime around the chain hardware, the brakes needed to be tensioned, and it had some out of order accessories. The accessories it had were a luggage wrack in the back which had a broken support (which is laying on the ground behind the bike in the picture), and a mechanical speedometer which had a loose cable and just made chirping noises. It also had "soft" plastic handle grips on the end of the dropped handle bars which were petrified and provided no cushioning.


I started by disassembling the whole thing! I cleaned all the parts with CLOROX(tm) disinfecting wipes because they have a cleaning agent which does no harm and are great for absorbing grime. I put the luggage wrack aside because it just got in the way of mounting/dismounting (and was broken). As for the speedometer, modern bicycle computers (speedometer, odometer, tripometer, etc.) are now inexpensive, under $12 at your local "superstore", and allow you to program your wheel size (unlike the mechanical one), so I replaced the huge speedometer with the little computer.


I took the wheels to the local bike shop and had them trued for $5/wheel. They still have a little jitter, but it's nothing compared to the thumping and wobbling that they had before. They had both lateral (off rotation axis) wobble and radial (tending to not form a circle) wobble. I can ride over 20 mph now and not leave the ground.


While the wheels were being worked on, I was able to remove the plastic grips a lot easier than I expected (these things have tendency to become attached). Rubber grips can be a real pain, but I figured the plastic grips would have been fused to the handlebars. I just inserted a flat-head screw driver (on the bottom side to avoid any visible scratching) in between the grip and the handle bar. I didn't pry with the screwdriver, rather just inserted and removed it several times, spraying WD-40 down the length of the screwdriver each time. After about three times, I was able to break each grip free by trying to twist the grip around the handlebar. Once it came free, I took out the screwdriver and worked it off. I cleaned the lubricant off the bars. I bought some handlebar gel tape from Bartrager, and installed them according to these directions since there were none in the box. I guess I have long handlebars because I didn't have to cut the length of the tape, I just made a cut to taper the distal end of the tape so it was flush with the handlebar cap.





The bicycle has a disk brake in the back which needed to be manually tightened because it didn't lock the wheel. The brakes in the front were also too loose. Tip: If brake pads don't lock the wheel, they need more tension. Take the wheel off of the frame, and ask an assistant to hold the pads together. If your caliper makes it easy to disengage the recoiling springs, you won't need an assistant. Taking the wheel off will provide enough slack to make the adjustment--I found it was impossible otherwise. Adjust where the steel cable is fastened on the caliper side about a centimeter and tighten everything back up.


The bike was back in order but the crank still felt bad because it moved inside the frame. It's a one-piece crank and is a lot simpler than I thought before. Take the chain off first. It has a big locking nut which you'll need a big wrench for. Note that the threads are in the opposite direction from most threads, so you take the nut off by turning it in a clockwise direction. Under that, there were some washers which act as dust covers. There is a big nut that the ball bearings ride on which needs to be finger-tightened, it was loose and this is where the crank wobble came from. I de-greased the ball bearings and the journals inside the frame. It was essentially dry inside just a lot of black deposits on everything. There was some fatigue on the right-hand (gear) side where the ball bearings either crashed down or the bearing retainer was hitting. With one-piece cranks, look inside where the crank fits and look for the obstructions from the other tubes. Find a place to fit the corner of the crank and angle the crank through as to take the gear away from the frame. This will give you more space and will let the crank rest. After everything was clean (I had to use an abrasive brush in some places), I greased everything up as much as I could and put everything back together. I used a screwdriver to make the final torque on the hand-tightened nut, I stopped as soon as I felt no wobbling of the crank. When you put everything back together, you should be able to spin the crank and it should keep spinning for a while. If it doesn't make it more than a few turns after you let go, it's too tight.


After a few other adjustments, like the kickstand position, everything was ready to go. The bike feels a lot tighter like a new bike would. All the rattling, chirping, and wobbling is gone.

The bike will need new tires soon (the thin tires don't last very long), I have about 300 miles on mine and the tread in the back is disappearing. When I replace these, I'll try to disassemble the bearings on the wheels and try to revive them like I did the crank bearings. I'll also replace the chain at that time.


Tuesday, July 17, 2007

Mount USB drives on boot

On Fedora Core 7, leaving a USB drive (a simple flash disk) connected doesn't seem to be mounting after reboot even though it's properly listed in the /etc/fstab. I went through a few solutions to this, like this one, but the only one that worked for me was modifying the /etc/rc.sysinit script as I explain below.

I seem to remember creating an entry in the fstab, and allowing the auto option (which is part of the default specification), would make your USB partition mount on boot. The issue with FC7 seems to be that the usb-storage kernel module isn't being loaded when the fstab is first loaded, and that the USB devices aren't initialized yet by /etc/rc.sysinit. This seems to be common with all newer distros, in accordance with the move to udev, hal and other components, which facilitate plug & play user mounting and they don't need them to be available before entering a GUI. This is great for workstations, but I have a "headless" server configuration, therefor I'm not using GNOME to mount anything on-demand, but rather they should be available statically.

After a few days of trial & error, and inspiration from this post, I added the following lines to the end of my /etc/rc.sysinit. Note that changes to this particular file may be removed by system updates (Using yum) as I explain below.
# Try to mount all USB partitions
# This should be moved to `rc.local' and be prepended with a wait
modprobe usb-storage
mount -a

I believe this is the most most robust method, since simply adding the entry to the fstab will allow it to be mounted after the USB devices are initialized. It is preferred to use the /etc/rc.local script to issue this nature of commands (local/custom configuration), but this script seems to be run before the /etc/rc.sysinit script exits, meaning the USB partitions may not yet be available. Commanding the /etc/rc.local script to wait for the /etc/rc.sysinit script to exit may be a solution.

Finally, note that you can guarantee consistency of the partition before mounting it by carefully editing the corresponding fstab line in the normal way, see man 5 fstab for more.

Saturday, July 14, 2007

Label your EXT3 partitions!

If you have removable drives used for backup or portable media, and you're using EXT3 rather than FAT16 (the default format of most USB flash drives), mounting these drives by their Linux device name is ambiguous. For example, I have a hard drive in a Venus DS-3 with a single EXT3 partition on it. The problem is, making the entry in the /etc/fstab file. The /dev/sd[a-z][1-9] designation is not good enough because it changes with the order of the connections during boot-time or plug-in time.

Making labels for each partition to be mounted fixes the problem entirely. To create a label for an ext2/ext3 partition, use the e2label command:
e2label [device] [label]

My exact command was:
e2label /dev/sde1 "Venus1"

Note that I had to find the right drive using 'fdisk' before I knew it was 'sde1'.

The change takes place right away, and then you can put a line in your /etc/fstab like:
LABEL="Venus1"          /media/venus1           ext3    noauto          0 0

And it will run through the drives to find the right label. We've associated the mount location with the partition on the physical device. This is especially important if you're mounting the drives on a server and are not using any automatic mounting facility.

Some recommend to also label the static partitions if you're using only EXT3. If you're using LVM, the groups and volumes are already labeled.

Alternatively, you may use a UUID, obtained from
udevinfo -q env -n /dev/sdd1

Where sdd1 is your USB device, which you can find from
fdisk -l


There is a lot more info you can get with udevinfo but for now, just grab the ID_FS_UUID and you can use it in your /etc/fstab as follows:
UUID=492bc203-de77-40b6-be4b-49e84fee430e /data ext3 auto,defaults 0 0


See http://www.patrickmin.com/linux/tip.php?name=usbkey_mount and
http://floatingsun.net/articles/howtos/howto-usb-automount.html for more.

Narrow-angle Panormas with Hugin


I have a telephoto lens and I wanted to stitch together several pictures of the Baltimore-Washington International airfield. Taking the pictures was just fine, although I hadn't learned how to set the exposure settings yet (see my post on this), and need to do it again on a clear day. What I didn't realize was that there's essentially no 'barrel distortion' with narrow-angle shots.

I found that it's hard for Hugin to figure out the angle of your shots when there's no barrel distortion. It misbehaves if you try to use the same procedure as you would for wide angle panoramas, and gives you completely insane average errors and if you try a preview--it won't be pretty. There are two things you need to do: tell it your horizontal field of view angle, and don't allow barrel distortion optimization. Only use "Positions and View (y,p,r,v)", and check that the barrel distortion stays close to 0.000 for now. This means that your panorama is essentially flat.

I was taking my panorama shots in portrait mode, which meant that my horizontal angle was 75% (the inverse of the aspect ratio 4/3) of the angle in landscape mode. That angle was about 8.10 degrees, and so the angle for each shot was 6.08 degrees. I got my focal length from the EXIF data, 224 mm, but the angle is most important.

Before final optimiztion and stitching, you may want to change the barrel distortion to something between 0.0034 and 0.006. This will add perspective to the panorama. Make sure you still don't run the optimizer for barrel distortion.

Panoramas with the Nikon D-50


This is a panorama I made while learning the following procedure for the Nikon D-50. These same instructions should apply to most Nikon Digital SLR cameras, and can be translated to most other digital cameras. In fact, I find that the huge resolution of my camera doesn't really impact the final product because you want most of the image to fit on your computer monitor, and you're literally multiplying megapixel area each time you take a shot (your canvas gets big quick)--so for close range panoramas, cheap digital cameras are fine as long as you can apply the following instructions to them.

The Nikon CoolPix series, unlike the Nikon D-50, has a Panorama Assist mode. This mode allowed you to take the first shot, which would set up the shutter, aperture and white balance for the rest of the shots. Then the right third of the last image would appear on the left-hand side and be semi-transparent. This allowed you to align landmarks and get good anchors for your stiching. The fixing of the shooting settings was also nice because it meant that the seems wouldn't be visible if you use a good panorama tool (see my post on Hugin).

However, the Nikon D-50 is more professional and didn't include such a mode. No matter! After reading over the manual, which is available on the internet (it was hard to find at Nikon's site, www.nikonusa.com), it was easy to piece together the same process as the 'Panorama Assist' mode.

How to do it:

Get a tripod and make sure it has a level. Set up the tripod and check the level before and after mounting the camera. Loosen the yaw all the way, and tighten the pitch and roll. Without a Tripod, you'll find that your panorama will actually be askew, and picking a level rectangle for cropping will leave you with a lot of wasted image area.

If you're shooting a large up and down angle and have the standard 300mm lens, roll the camera and shoot portrait shots. This means if you don't rotate each shot, you might be stichting tops and bottoms of images in Hugin, which is counterinuitive, but you can rotate the anchor in Hugin later and everything will be fine.

Since we're post-processing the images, you should use 'Fine' mode. You don't have to use 'Raw', and in fact I noticed no real difference between 'Raw' and 'Fine' modes for this application.

The the 'M' mode on the mode dial means 'Manual Mode'. So, you just put the camera into this mode, and the shooting settings (shutter speed and aperture) are fixed.

Note that being in Manual Mode means the camera is not doing anything for you! You'll have to find some angle in your panorama to set the exposure settings until the exposure meter says zero. I favor the angle closest to the sun, but don't let the sun enter the frame. This will leave the dark portions of the panorama underexposed. The exposure meter is inside the viewfinder along the bottom. Rotate the winder on the right-hand side as you normally would to change the shutter speed and find the fastest speed that gets the reticle inside the meter. Then hold down the button on top, next to the power switch, shaped like an iris and rotate the same winder to adjust the aperture. Repeat the process until the reticle in the exposure meter is at zero.

On other thing you'll want to do is find a target at nominal distance to focus (or perform an auto focus) on. Then switch the camera into manual focus mode, since we don't want it to change. Don't accidentally change the focus.

Now you can start snapping away. Pick the most left angle and shoot, then change the yaw of the camera keeping a landmark that was on the right-hand side in the frame. Don't share too much of the yaw angle with the previous frame or you'll take too many pictures. Don't share too little or you won't have enough landmarks (common features) to teach the panorama tool how to stitch them together. You'll get the hang of it.

Finally, load the pictures onto your GNU+Linux workstation (or Windows, bleh) and import the series of shots into Hugin. http://hugin.sourceforge.net/

Hugin Deserves a Hug!


Yes, I know other bloggers have already written in depth about Hugin, but I'd like to share my experience.

First of all, Hugin is just a graphical front-end for already established panorama libraries (which I didn't know existed) called panotools. Before, I would piece together a panorama by hand with The GIMP, but that never made the edges seamless, and never accounted for the lens barrel distortion.

The official page:
http://hugin.sourceforge.net/

They have plenty of tutorials to get you started. The program is not overcomplicated and you can get the hang of it rather quickly (make sure you are following the tutorials). It's just a matter of teaching the panorama tool how the images fit together and how the camera distorts the landscape.

The panorma shown was taken with a Nikon Coolpix 5400 in Panorama Assist mode some time ago. I hadn't been able to see the pictures stitched together because of the intensity of the barrel distortion, but with Hugin, it was a snap!

More process-specific posts on Hugin to come.

Announcing New Bliggity Blog

Assuming that anyone might read this, I just want to make this post to announce that my blog will no longer be strictly GNU+Linux and computer tips. It will still be related to these topics, but posts on 'how to do this' either with a GUI or from the command line are getting too scarce. Note that I will start to use 'labels' (aka 'tags') so that you can still filter out all but a certain topic.

Wednesday, May 16, 2007

Pesky Windows "Thumbs.db" Files

Windows creates a Thumbs.db file whenever it finds an image in a directory. If you are trying to reduce the number of files on your file system, or trying (really hard) to save space, you can issue the following commands as administrator.
locate -r ".*/Thumbs.db" > ~/delme-thumbs.txt

Which queries the mlocate database for the thumbnail files. If you're not running mlocate, you would use the find command here.
cat ~/delme-thumbs.txt | tr \\n \\0 | xargs -0 du -hsc

This will show you how much each file is taking up and include a sum of the total size. Finally, you might want to free these files with the following command:
cat delme-thumbs.txt | tr \\n \\0 | xargs -0 rm