Wednesday, December 28, 2011

Kindle conversion

I got a Kindle for Christmas! (thanks Granny). However like many people I ran into the problem with converting .epub to .mobi where the converted files have huge margins on the left hand side of the screen. After some research I found a series of forum post suggesting various solutions but all of them were very manual processes and I wanted something that would just do it for me.

So what I've got here is a simple shell script that does it all for you. You will need to install calibre since it uses the command line tools from that to do the actual conversion but it will automatically convert and sort the formatting out for you.

I'll probably end up redoing it all in python so that it will work on windows.

mkdir _temp
mkdir converted

for file in "$@"
do
echo "Converting \"$file\""

cp -f "$file" _temp/.

filename=$( echo "$file" | sed 's/^.*\///' )
file_type=$( echo "$filename" | sed 's/^.*\.//' )
new_file=$( echo "$filename" | sed 's/[^.]*$/mobi/' )

# if .epub
if [[ $file_type == "epub" ]]
then
# if the metadata is lacking language information then set it to en
lang_meta=$( ebook-meta "_temp/$filename" | egrep "^Language" )
if [[ !( -n "$lang_meta" ) ]]
then
echo "Changing metadata language"
ebook-meta -l en "_temp/$file" >/dev/null 2>&1
fi

# edit the stylesheet to get rid of the massive gap on the left
unzip -f "_temp/$filename" stylesheet.css >/dev/null 2>&1
sed -i 's/margin-left:.*;/margin-left: 0;/g' stylesheet.css
zip "_temp/$filename" stylesheet.css >/dev/null 2>&1
fi

ebook-convert "_temp/$filename" "_temp/$new_file" > /dev/null
#wine kindlegen "_temp/$filename"

mv -f "_temp/$new_file" converted/.
done

rm -r _temp

Monday, February 14, 2011

NXT and I2C

Lets face it I am a terrible blogger, but no one reads this anyway so who cares.

Anyway recently I had some serious grief getting a Devantech CMPS03 digital compass to work with a Lego NXT. The info doesn't appear to be anywhere else on line and I couldn't find a decent I2C example in nxc.

Here is some basic code showing how to get it working.

#define cmpAddr 0xC0 // Machine address of the compass
#define cmpPort S1 // Port that the compass is plugged in to

byte bufLSWrite[] = {cmpAddr, 0x01, 0xC1}; // Written to the compass... (Compass, give me data from register 1, now)

// Take a compass reading
int compassReading()
{
byte r;
byte outbuf[1];
byte byteNumber;
int result;
byteNumber = 1; // Read byte 1

while (I2CCheckStatus(cmpPort) == STAT_COMM_PENDING);

if (I2CBytes(cmpPort, bufLSWrite, byteNumber, outbuf))
{ r = outbuf[0];
}
else
{ r = -1;
}

result = r;

return result;
}

task main()
{
int reading;
int counter = 0;

SetSensorLowspeed(cmpPort);

while( true )
{ reading = compassReading();

NumOut( 1, LCD_LINE1, counter++, false );
NumOut( 1, LCD_LINE3, reading, false );

Wait(1000);
}
}

This is actually just a stepping stone to getting the sensor to work via NXT++ from my netbook but I'll post that code later.