20120601

Let There Be Music


I needed to be able to play MP3 files as part of a larger project I'm working on.  I did a quick search on the Internet for embeddable MP3 player chips and circuits, but everything seemed a bit too expensive or too much work.  It was around then I saw Hack a Day's post pointing me to Gadget Gangster's Instructables article Adding MP3 to your project for $3.00.  Being the cheapskate that I am, $3 sounds great to me!

A quick trip to eBay and I had two of these “mini-clip” players on the way.  I figured I should get an extra just in case I damage one while fooling around.   Before I began hacking the player, I tested it out to make sure it was operational and get an idea of how it behaves.  One of the things I discovered is that the USB interface is pretty flaky (at least when connected to a Linux system), so it was much easier and faster to transfer files onto it by writing directly to the MicroSD card using a card reader.

Player liberated from its case

I cracked one open and took a look to see what it would take to hook into it.  One of the things I wanted to do is to be able to move this from prototype to finished product, or between projects.  The Instructables article showed discrete wires soldered to the board, which I could have brought out to some kind of connector.  After a bit of thought, I realized I could use a small 10 pin IDC connector and ribbon cable to allow me to plug it into a nice wire-wrappable header.  And with the extra pins, I could also supply power, and even pick off the audio!

After some minor surgery

First, I removed the power wires and also carefully removed the surface mount audio connector.  Somewhere in my lab I have the parts to build the IDC/ribbon cable assembly, but I found a pre-made one in my parts bin so I just cut it in half and started peeling back a few of the wires.

IDC cable ready for action
 I started by connecting to the power pads (mostly because they were big and easy to get to).  This also conveniently allowed me to set the amount of overhang from the connector to the board.  I then cut and stripped the remaining three wires for that side and landed them onto the pads where the audio connector used to be.  Next, I flipped over the board and cut each of the wires to length and soldered them to the center of each button pad.

Wires landed on board

Now with all the wires hooked up, it's time to test it out and see if I fried anything.  I wired up a 2x10 header on my main project (more about that in a future post) and wrote some quick code to “push” the buttons.

At home in the new project

I'm using a PIC18F4550 in this project, and using my favorite language – assembly. I love the challenge of hand-tuning code to make it as small and fast as possible, and that's not so easy with the PIC18F's!  Anyway, I wanted to drive the switch outputs open collector style, so for the switch outputs I initialize the ports by setting the switch TRIS bits and clearing the LAT output bits.  Then when I want to “press” a switch, I clear the the corresponding TRIS bit which drives the output low, and set a tick countdown timer.  When that timer expires about 200ms later, I set all the TRIS bits again to “float” the outputs and release all the switches.

After checking to make sure the software was doing as I expected, I connected the MP3 player to the main project, powered it up, and out came music!  I then tested each of the switch functions, and the player responded as expected, pausing, playing, skipping forward and back, etc.  To my surprise, everything worked as expected.  The player has been working without any hiccups for several months, despite powering it with 5v instead of it's expected 3.7v battery, and shorting the switch inputs to ground instead of the other contact (although I expect that is the way it is wired anyway).

I would like to thank Gadget Gangster for sharing his cool tip to re-purpose cheap MP3 players for use in embedded projects, and Hack a Day for bringing it to my attention.

Read More......

20110827

Hacking WebRunner to work with Firefox 6.0

I have come to depend on Salsita Software's WebRunner extension for Firefox that let's me create “applications” out of web sites. It comes in especially handy when I want to be logged in with multiple identities on the same web site, as well has keeping an always open window on my Zoneminder cameras.

When Firefox 6.0 was pushed out in Ubuntu, I was quite dismayed to find that when it checked add-ons and extensions for compatibility, WebRunner was not compatible, and furthermore, an updated version was not available. I waited for around two weeks for Salsita to update their software, but so far there's been nothing. So I dug around in the .xpi file and came up with this hack to make the current version work with Firefox 6. These instructions are for Ubuntu/Linux (since that is all I have running now), but the changes should be very similar for Windows as well.

First download (but don't install/run) the latest .xpi file from here. Then open the file with an archive manager (.xpi files are really just jar/zip files) and edit the file install.rdf, changing the value of /RDF/Description/version from 5.0 to 5.1, and the value of /RDF/targetApplication/maxVersion from 5.* to 6.*. Next, edit the file stub/application.ini, changing the value for MaxVersion from 5.0.* to 6.0.*. You may want to rename the .xpi file at this point to make it easier to keep track of it.

Now update to Firefox 6.0 (if you haven't done so already) and remove the old WebRunner 5.0 extension, in Tools|Add-ons on the Extensions tab. Close that dialog, and go to File|Open File... in Firefox and select your modified .xpi file. It should install without complaint, indicating it is version 5.1 (hopefully Salsita will version their next release higher than this).

At this point, you can either re-create your web application shortcuts, or hack the existing ones to work with the updated extension. To fix the current shortcuts and applications, modify the command for the shortcuts to point to firefox-6.0 instead of firefox-5.0. Then for each application in your ~/.webapps directory, edit the appname@webrunner/stub/application.ini file and change MaxVersion from 5.0.* to 6.0.* and change GRE_HOME to /usr/lib/firefox-6.0. Now try to launch your web application shortcuts and you should be good-to-go!

As with most hacks, I make no guarantees that this won't in some way hose your Firefox installation or your entire computer, so attempt this at your own risk! On the other hand, if you are like me and depend on the excellent WebRunner extension, this hack is a quick way to get it back in Firefox 6. Make sure to leave comments if you have tried this under Windows and get it to work.

Read More......

20100918

Dependency Injection Using Nested Classes

In my day job (lately it seems to be a 24 hour day) I do most of my work in C#, and all our new projects are implemented using Test Driven Development. Like most people doing TDD, we need to inject mock/stub/dummy objects into our objects under test. The traditional way to accomplish this is either via Constructor Injection or Setter Injection.

I have never been a fan of using setters to inject test objects, because it clutters the code with properties and methods that are only used for testing and are never used by production code. At first, I relied on constructor injection, but would sometimes run into cases where I was passing in half a dozen or more objects into the constructor. Many of these objects were simply helper classes that bundled up some functionality needed by the object under test only, and would never normally be used outside of that class.

Over the last year we have evolved another way of injecting mock objects into our test objects – Nested Class Injection (or as we call it, “TestHook Injection”). In C#, a nested class has access to it's containing class's private members, so we can use methods on the nested class to reach into the private details of the outer class. Here is a simple example:

    public class ObjectUnderTest {

private IHelperObject _helper;

public ObjectUnderTest() {
_helper = new ProductionHelper();
}

public bool MethodToTest(int testNumber) {
return _helper.HelperMethod(testNumber);
}

public abstract class TestHook {

public static void InjectObjectHelper(ObjectUnderTest objectUnderTest, IHelperObject helper ) {
objectUnderTest._helper = helper;
}

}
}


Now all the test related code is contained within the abstract TestHook class. This class acts like the diagnostic connector on your car, allowing access to internal data and manufacturer's info without exposing it to the user. In fact, you can even use conditional compilation to exclude the TestHook class in the release build to remove the “connector” if code size or security is an issue.

Now when you are ready to test your objects, you can do something like:
        [Test]
public void Test_MethodToTest() {
ObjectUnderTest objectUnderTest = new ObjectUnderTest();

IHelperObject mockHelperObject = new MockHelperObject();
ObjectUnderTest.TestHook.InjectObjectHelper(objectUnderTest, mockHelperObject);

objectUnderTest.MethodToTest(12);

// Test expectations here...
}


Note that I do not normally create my own mocks as shown above, I typically use Rhino Mocks to create mock objects, and Ninject as my IoC container. The contrived examples above are just to show the basic technique of using a nested class to cleanly access the internals of an object for testing purposes.

Now injecting objects like this is really only useful when those objects are only going to be used internally by the class under test. If you need to pass in an instance of an object that is shared between multiple objects, traditional constructor or setter injection is fine, since that is actually part of the object's contract with the world.

We have been using this technique for several months now, and it has resulted in cleaner production code, and more streamlined testing. Our test setup methods are simpler now, because we only need to inject mocks in the tests that need them instead of in the common test setup method.

I figured I should write this up since I have found the technique very useful, and a quick Google search didn't turn up anything useful. I expect this can be used in any language that supports nested classes where the nested class has access to the outer class's private member variables. Let me know in the comments if you find this technique helpful, or have any improvements. Thanks for stopping by!

Read More......

20100516

Me Day

As a special treat for myself, I recently escaped from the Teknynja Cave to visit JPL's 2010 Open House. This was my first time visiting Jet Propulsion Laboratory or the open house event, and it was even better than I expected. As a science and space enthusiast, there where plenty of things to see. What I didn't expect was the festival atmosphere and all the activities and displays for kids and families. There was plenty of booths selling kettle corn, hamburgers & hot dogs, frozen lemonade and other treats, and the smells were like that of any “normal” festival.




My first stop of the day was the Space Flight Operations Facility, the “Mission Control” room, where spacecraft like the Viking, Pioneer, Voyager and the Mars Rovers have been monitored and controlled. It was exciting to see this room with so much history (and to be in the presence of so many computer monitors).






Next up was a short shuttle bus trip to the 25 Foot Space Simulator facility, a giant environmental chamber that simulates the conditions found in space or on other planets. Spacecraft are placed inside the simulator and subjected to the vacuum and heat of space. You can walk around inside the huge chamber, and I also enjoyed checking out the control room for the simulator.




One of the highlights of my trip was visiting the Spacecraft Assembly Facility, a enormous clean room where JPL's probes and landers are built. It was especially exciting for me to see the Mars Science Laboratory (still in several pieces), which is scheduled to arrive on Mars in 2012.



The big draw for me though, was the Hubble Wide Field Planetary Camera 2 exhibit, which displays the actual camera that flew on the Hubble telescope from 2002 until 2009. Being this close to actual space hardware was an amazing experience! It is difficult to really see it in this photo, as it is enclosed in a protective nitrogen gas environment. This exhibit is the centerpiece of the new museum on the JPL campus, that contains dozens of models of probes, rovers, and landers.



At this point in my visit, the lines were starting to get very long, but I didn't mind. My next stop was the Spacecraft Fabrication Facility, where the components for spacecraft are machined and manufactured. The amount of manufacturing and machining technology in this building is overwhelming, and the tables showing example parts was very impressive.



I finally ended up at the Micro Devices Laboratory, where they do everything from create nano-sized machines to electronic chip fabrication. There was plenty to see there, but this room caught my eye - this would be my dream office, with wires and electronic equipment everywhere. Maybe someday...







I wrapped up my trip taking in the architecture and the festival scene before hitting the “gift shop” to pick up a tee shirt and some swag for the kids. I really only hit about half the activities at the open house, but saw what I came to see and more. I'll have to go again, and next time I'll probably bring the young'ins along as well.

Read More......

20100307

std::string and sprintf

Amongst the many projects I am currently juggling, one of them involves developing some C++ code for an embedded Linux project. I've just hit an instance where I'd like to be able to use “printf” style formatting using std::string instances, but it can be pretty clumsy – I need to allocate buffer space for sprintf, invoke the function, and package up the result into another string.

I did a quick search on the Internet and found many others looking for the same thing: “Is there a way I can use sprintf in c++ using std:strings?” And invariably the answers were either


  • “No”

  • “Use std::ostringstream and c++'s built-in manipulators”

  • “Use boost::format

And they are all right!

It turns out that you can't safely use the *printf style variable argument lists with C++, as only POD (Plain Old Data) types can be passed in the list. Attempting to pass most other types will result in a segmentation fault at run time. The official C++ way is to use ostringstream and the usual stream manipulators to format parameters, but for me, that make's writing tests more difficult because I need to “build” the expected streams exactly the same way in my test code. The final method could work for me, except that this is an embedded project and I am trying to keep the number of libraries referenced to a minimum, since I need to build and include them on my target Linux system.

So my solution was to accept the limitations of the printf function and write a wrapper function that hides the buffer setup and string creation:

#include <string>
#include <stdarg.h>
#include <stdio.h>

string FormatString(const string& format, ...) {
char buffer[1024];

va_list arglist;
va_start(arglist, format);
int length = vsnprintf(buffer, sizeof(buffer), format.c_str(), arglist);
va_end(arglist);

return string(buffer, length);
}



I've tucked this away in a nested namespace so I can invoke it easily when needed. Now when I need formatted text I can just supply a c string or std::string format and my parameters, and get back a nice std::string instance in return. But there's a catch! I can't pass in a std::string as a parameter because the old-school c variable argument list can't handle objects. If I try to do that, I will get a “warning: cannot pass objects of non-POD type 'struct std::string' through '...'; call will abort at runtime” warning and a segmentation fault at runtime. The work around (at least for std::string objects) is to invoke the c_str() method on the string parameter instance. So for example

    string argument = "a string instance";
string result = FormatString("I can format a %s parameter!", argument.c_str());


allows me to supply std::string arguments as well. The c_str() function returns a pointer to a temporary buffer containing a c style string version of the string object's value.

So now I have my template style formatting and I can move on with my project. This project is my first foray into any substantial C++ programming, so if you seen any glaring problems or know a better solution, or if this little tip helped you too, please let me know by leaving a comment.

Read More......

20091006

MonoDevelop Custom Color Schemes

I have been playing with MonoDevelop 2.0 on Ubuntu on and off for a while now, but one of the things I find most annoying (other than not having ReSharper) is there is no easy way to modify the colors used for syntax highlighting. Sure, it has several pre-defined schemes you can choose from (Using Edit | Prefrences > Text Editor > Syntax Highlighting), but changing individual syntax element colors using the GUI is not possible.


The reason I find this issue annoying is that I like to have comments and strings really stand out – in our shop we avoid comments as much as possible, and string constants are kept to a minimum, so I like to be able to see them easily in the code. A few years ago, I started using “highlighter” background colors for comments and strings, and have become quite attached to them ever since.


After many attempts to find a solution on the web, I finally found all the pieces I needed to make it happen. The basic problem is that although MonoDevelop allows you to add new color schemes, the format of the scheme file is not well documented, and there are a few tricks you need to know to make it work correctly. The existing schemes are embedded resources and not stand alone files, so they can't be easily viewed for reference. Finally, I discovered this Ubuntu Forum thread that helped me find the solution. The first piece of the puzzle was discovering the color scheme XML source files in MonoDevelop's SVN tree. Now I had some samples to go by. Another useful tidbit from that thread was that the file name must end in "Style.xml" in order to work correctly. I did not actually verify that this was required, but I did it just to be safe. The rest came from a MonoDevelop Developer's Article page I stumbled across shortly thereafter. One of the important things mentioned on that page is that you need to put the color scheme XML file in the ~/.config/syntaxmodes directory (although in my Ubuntu installation it is actually ~/.config/MonoDevelop/syntaxmodes). Now I had everything I needed to start tweaking colors!

The first thing I did was download the VisualStudioStyle.xml file and renamed it to TeknynjaStyle.xml. Next I edited the file to change the name and _description attributes of the EditorStyle tag so they would not clash with the existing styles in the GUI. Finally, using the information from the MonoDevelop article and the existing examples, I modified the colors for comments and strings to get the highlighting I was looking for:

   <Style name="comment" color="black" bgColor="#ffff80"/>
<Style name="comment.doc" color="black" bgColor="#ff8040"/>
<Style name="comment.tag.doc" color="black" bgColor="#ff8040"/>

<Style name="text.preprocessor" color="purple"/>
<Style name="text.markup" color="skyblue"/>

<Style name="constant" color="black"/>
<Style name="constant.language" color="keyword-blue"/>

<Style name="string" color="black" bgColor="#80ff80"/>
<Style name="string.single" color="black" bgColor="#80ff80"/>
<Style name="string.double" color="black" bgColor="#80ff80"/>
<Style name="string.other" color="black" bgColor="#80ff80"/>

<Style name="keyword" color="keyword-blue">
<Style name="type" color="#004080"/>
</Style>

I found the "bgColor" attribute by looking in one of the other color scheme files. Then I copied my customized color scheme file to ~/.config/MonoDevelop/syntaxmodes, restarted MonoDevelop, and selected my color scheme. I was able to tweak the colors by editing the XML file and restarting MonoDevelop until I achieved the scheme I was looking for. Finally I had the highlighting I was used to in Visual Studio, and along with modifying some of my commonly used key bindings, I was able to make MonoDevelop feel a little more like "home".

Read More......

20090603

To Protect and Surf (dnsmasq and Whitelists)

Contrary to popular rumor, I am still alive and very busy – from about October of last year until last month I have been buried at work (a good thing in this economy!). Maybe now that I can see a little daylight, I can try to keep this blog updated a little more frequently. Enough with the excuses and on with the post.

The only person in this house that likes to spend more time on the computer than me is my 4 year old son. Most of the time he is content to play an old copy of Monster Truck Madness 2 that I picked up years ago, but he also likes to spend time at Dan-Dare.org, Playhouse Disney, PBS Kids, and several other sites. The problem (other than trying to limit his time on the computer) is that he also likes to explore. When he gets bored just playing the games, he's off checking out what each menu item and dialog box does. He has explored all the configuration options in the monster truck game, and he is always playing with the volume control applet – I've spent plenty of time trying to undo his changes on the kid's computer. Lately, he has also taken to checking out the various links on the websites he visits. A couple of times he has run in to inform us that we can get a free monster truck game, and when we go check on him he has wandered off to some obscure website. Well, it happened again today, and although I've always known I would have to take action, today was the day to do something about it.

Being the cheap bastard that I am, I needed a free solution that would keep him (or my 7 year old daughter) from visiting places on the web that I would rather not have them be for now. I decided that what I need for now is a DNS forwarder with a whitelist, so that only the sites on the list can be accessed. Although the following solution is fine for small kids, anyone with an 8088 for a brain can figure out how to get around this. Even so, it should work for us for the next few years.

A little surfing pointed me to dnsmasq, a very popular dns forwarding server. A little more research indicated that using it to whitelist domains was not easy – there is no built-in way to do it. I found someone who listed a source patch to make it happen, but I didn't want to go to that extreme if I could avoid it. Despite this, I went ahead and installed it on my file server (running Ubuntu, of course) using sudo apt-get install dnsmasq. Looking at all the options in the man page and in the /etc/dnsmasq.conf file was overwhelming at first, but it didn't take too long to figure things out. One of the things I discovered was that you can assign specific outside DNS servers for specific domains. I realized that if I blocked off any other way for it to resolve domain names except for this feature, I could use it like a whitelist! A little experimenting proved that it did indeed work. Here is the dnsmask.conf that I am using right now:

domain-needed
bogus-priv
log-queries
log-facility=/var/log/dnsmasq.log
no-resolv
interface=eth0

# Add other name servers here, with domain specs if they are for
# non-public domains.
#server=/localnet/192.168.0.1
server=/google.com/192.168.0.1
server=/dan-dare.org/192.168.0.1
server=/dan-dare.net/192.168.0.1
server=/pbskids.org/192.168.0.1
server=/playhousedisney.com/192.168.0.1
server=/disney.go.com/192.168.0.1
server=/starfall.com/192.168.0.1


The first few lines do the actual configuration of dnsmasq, domain-needed & bogus-priv block Windows machines from passing noise traffic, log-queries & log-facility tell dnsmasq to log all DNS requests to the /var/log/dnsmasq.log file (useful for determining the domains required by websites, but this can be turned off to save space), no-resolv tells it to ignore the resolv.conf file which usually lists the outside DNS servers to use, and finally interface tells the service which network interface to bind to.

The rest of the “server” lines implement the whitelist, telling dnsmasq to look for the specified domain's IP address using the specified DNS server. In this case, I simply pointed to the DNS server in my local network's router (192.168.0.1). Any other domains are simply returned as being invalid. To populate this list, I simply attempted to browse to the sites my children visit, and then looked in the /var/log/dnsmasq.log file to see what domains were being requested, then entered them into the dnsmasq.conf file. After each update to the configuration file, I needed to sudo /etc/init.d/dnsmasq restart to get the service to re-read the file.

The final step was to change the DNS server address on the kid's computer to point to the file server's IP address, and that was it – now anytime they “accidentally” try to access a domain not in the list, they get a message saying the domain was not found. Of course any computer-savvy person could simply set the DNS server to something else (like OpenDNS!), but it will probably be a few years before my kids figure that out. If they want to visit someplace new, I have to intervene (which is what I want). In a few more years, I will have to be more creative to keep ahead of the kids and to keep my workload down updating the list – but for now this works for me.

So hopefully, if there are other people like me searching for a way to add whitelisting to their dnsmasq forwarders, maybe this post will be a starting point. If you have any questions, go ahead and leave me a comment or send me an email, I'll do my best to help. And maybe if things slow down a little there will be more frequent posting around here as well.

Read More......
 
Template design by Amanda @ Blogger Buster