DaedTech

Stories about Software

By

Poor Man’s Automoq in .NET 4

So, the other day I mentioned to a coworker that I was working on a tool that would wrap moq and provide expressive test double names. I then mentioned the tool AutoMoq, and he showed me something that he was doing. It’s very simple:

 [TestClass]
    public class FeatureResetServiceTest
    {
        #region Builders

        private static FeatureResetService BuildTarget(IFeatureLocator locator = null)
        {
            var myLocator = locator ?? new Mock().Object;
            return new FeatureResetService(myLocator);
        }

        /// If you're going out of your way to pass null instead of empty, something is wrong
        [TestMethod, Owner("ebd"), TestCategory("Proven"), TestCategory("Unit")]
        public void ResetToDefault_Throws_NullArgumentException()
        {
            var myService = BuildTarget();

            ExtendedAssert.Throws(() => myService.ResetFeaturesToDefault(null));
        }

The concept here is very simple. If you’re using a dependency injection scheme (manual or IoC container), your classes may evolve to need additional dependencies, which sucks if you’re declaring them inline in every method. This means that you need to engage in a flurry of find/replace, which is a deterrent from changing your constructor signature, even when that’s the best way to go.

This solution, while not perfect, definitely eliminates that in a lot of cases. The BuildTarget() method takes an optional parameter (hence the requirement for .NET 4) for each constructor parameter, and if said parameter is not supplied, it creates a simple mock.

There are some obvious shortcomings — if you remove a reference from your constructor, you still have to go through all of your tests and remove the extra setup code for that dependency, for instance, but this is still much better than the old fashioned way.

I’ve now adopted this practice where suitable and am finding that I like it.

(ExtendedAssert is a utility that I wrote to address what I consider shortcomings in MSTest).

By

Getting Started with Home Automation

I’m going to be doing a series of posts on home automation, starting out targeting beginner concepts and getting more in depth from there. My hope is that when these are complete, someone with some technical and home improvement acumen can read back through the series as an instruction manual of sorts.

What Is Home Automation?

Home automation is somewhat hard to define. Out of curiosity, I poked around and found as many different definitions as places offering definitions. The definition I most liked came from ehow:

Home automation [allows] individuals to automatically control appliances and security systems within their home through the use [of] technology.

Other sites talked specifically about the use of computers and various products, but this one is nice and general. To my way of thinking, home automation is the use of any technology that helps automate tasks in the home. This may include turning on lights, starting appliances, opening blinds, etc. So, anything from the “home of the future” to The Clapper can be considered home automation.

A Brief History

The concept of home automation has been around for a long time. In the early 1900s, the “house of the future” was the stuff of speculation at world fairs and in the studios of inventors. No doubt many interesting concepts came out of that, but nothing particularly interesting for our purposes here (though one might pedantically argue that appliances such as dishwashers or devices like thermostats are a form of home automation). As the 1900’s wore on, the concept of remotely controllable devices, such as televisions emerged, providing a relatively early snapshot.

In 1975, a Scottish company called Pico Electronics developed the X10 protocol. This was a way to use existing electricity wiring within a house for communication between a sender and a receiver. This protocol was used to transmit simple messages across the wire. A controller could send an “On” message and a device elsewhere in the house would receive this message and execute some appropriate action. For exmaple, a “lamp module” plugged into a wall and with a lamp plugged into it could turn on the lamp at the request of a signal sent from another room.

Over the course of time, the uses of X10 technology expanded from simple on and off to signals allowing control over home security, heating, air condition and ventilation (HVAC) and other home technologies. X10 is reliable and established, but it does have some limits, and those limits have become more obvious lately as the number of devices using house power have skyrocketed. Devices, especially modern ones tend to produce “noise” on the electrical lines, and the more devices we plug in the more noise is generated.

A number of other protocols and technologies have emerged as a result of this, including Insteon, Z-Wave, Lutron and more. And, there is still X10 itself, which is a little confusing as it is both the name of a protocol and the name of an organization that sells devices that implement the protocol. The newcomers tend either to use a different protocol over the electrical system (some being “backward” compatible with X10 and others not) or else to use wifi communication. Often these are more effective than the original X10, but also pricier.

For a time in the 80’s and 90’s, big box stores like Radio Shack and Home Depot carried X10 products, but that seems not to be the case anymore. Some of them now carry the higher end competitors such as Lutron and Insteon. But, if one is interested in purchasing any of these devices, you can find them in many places for ordering online, including ebay.

The fact that you don’t find these items for sale in big box stores does not mean that the home automation trend has cooled off, per se. As society expects more and more things to be automated, the home is no exception. The reason that these items are not carried so much anymore, in my opinion, is that the average consumer is not a combination of electrical engineer and carpenter. People want devices that they can plug in and have “just work” with a minimum of configuration. So, people hire contractors to wire these sorts of things up for them, rather than simply buying them at the local hardware store.

Our first crack at home automation..

So for anyone still reading, sold, and ready to jump in, I will introduce a first home automation project that you can execute as an absolute beginner. You’re going to buy two items, and it’s going to cost roughly $25 to $30, depending on where you order. One item is a keychain, and the other is an X10 “lamp module” with a wireless transceiver. They are pictured together here:

(You can buy this setup on Amazon for $30 at the time of writing, though a quick google search showed prices as low as $16, though that may be omitting a shipping charge).

When you get the devices in the mail, take out the lamp module and observe that it has a red dial on it. The red dial corresponds to the “house” code, one of 16 letters. All X10 devices have a house code and a unit code, and these together form the “address” of the device. The house code, as mentioned, is one of 16 letters, and the unit code is one of 16 numbers. This means that X10 addresses are A1, D12, J4, etc. Your lamp module has all available house codes, but only has unit codes “1” and “9”. These are the unit codes that it will respond to if you were sending commands over the electricity, but it will respond to any unit code sent wirelessly, which is how your remote will work.

If you now take out your remote and its instruction manual, you will see that you can set it to send signals to any house code and unit code. The unit code is essentially irrelevant here for your purposes. You just want to make sure the house code matches the lamp module’s. At this point in your home automation ventures, these are the only devices you have, so just leave them both at house code A.

Now, plug a lamp into the lamp module and the module into the wall. You should now be able to turn your light on and off using the keychain. The range on this should be comparable to that of your home wifi, so you could turn the lights on in your house from your car in the driveway or garage, which is handy.

So, to recap, you can basically just unwrap the devices and set them up without messing with the unit or house codes at all, since your lack of other home automation stuff means you don’t need to worry about compatibility. You now have home automation going for $25 or $30. If you’re interested in doing more, no worries – I’ll have plenty more segments on this.

More Info

For now, I’ll leave off with a series of links that I’ve found over the course of time that will hopefully be helpful, but not too overwhelming.

And, no worries if I haven’t covered all bases – I’ll have plenty more posts.

Cheers!

By

Dell Keyboard Failure

The Symptoms

This is yet another entry of the “hope this saves someone time and aggravation” variety. I’m adding a new category called “Lessons Learned” that I’ll be tagging these with going forward.

So, I was playing Civilization V and I stepped away for a few minutes to find the screensaver on when I came back. I moved the mouse and nothing. Enter key and nothing. Ctrl-Alt-Delete, nothing. Several minutes of angrily mashing my keyboard and, not surprisingly, nothing. Given the graphics-heavy nature of Civ V, I assumed that my machine had crashed (this happens sometimes with Civ V), so I rebooted.

When I did that, I was greeted by the image above. So, I figured my wireless keyboard had run out of batteries and I went all the way down to the basement, grumbling, got new triple As and slapped them in. Rebooted, and keyboard failure. Tried a different USB port and keyboard failure. Tried my keyboard in another machine and success! Uh, oh. To the interwebs!

After googling around, I didn’t find any definitive solution. There were some scorched Earth suggestions, my favorite of which was “replace the motherboard”. There were some shotgun suggestions involving running without a CMOS battery, bending USB pins, switching the wireless receiver around from port to port, and various other procedural mumbo-jumbo that had probably coincidentally worked for someone somehow.

The Solution

I got lucky, though. The first scattershot step I took seemed the simplest, and it worked, so I know exactly what worked. I powered down and disconnected from power, and then popped a two pin jumper off of a three pin block on the motherboard for a few seconds and replaced it. Viola!

Appropriate disclaimers about unplugging and discharging capacitors and all that other stuff that I never remember to do but wouldn’t want somehow to be liable for you not doing it. But, that did the trick. Back up and running with no new keyboard, and certainly no new motherboard. Excuse to buy a new machine averted… (d’oh!)

By

Compiling XML! (Not really)

So, here’s another one filed in the “hope this saves someone some grief” category. I was cruising along with my home automation ‘droid app, setting my layouts and wiring up my button click handlers, when all of a sudden, I was getting weird build errors about. I couldn’t run or even build. When I tried to build, I got messages about different things being redefined in my main XML layout file. This was strange, since I hadn’t edited it directly, but was using the graphical layout tool.

As I inspected the errors more closely, I began to understand that there was apparently some rogue XML somewhere. A bug in Eclipse? With the Android SDK plugin? Had I been hacked by someone with a very strange set of motives? I opened up my layout folder and this is what I saw:

Wat?

After some googling around and experimentation, I discovered that this file is generated if you run with the Play icon and the XML file open as your selected window in the editor. Perhaps that’s something that Eclipse users are used to, but coming from a pretty solid couple of years of Visual Studio, this had me mystified. So, lesson learned. Don’t run if you have XML open in Eclipse (or anything else you don’t want slapped with a .out between filename and extension and apparently included in compilation.

Cheers 🙂

By

Android: Let There Be Internet!

I’ve been a little lax in documenting my experience as a neophyte Android developer, and for that I apologize. Tonight, I have a quick entry that will hopefully save you some time.

I’m working on an open source home automation server. I’ve had a prototype functional for a couple of years now that runs as a web server in apache, Java-based, and controls the lights through a web interface front end and a low level backend that interfaces with the house’s electrical system. I control this through any computer/phone/ipod/wii/etc that’s hooked to my home wifi, using the browser.

Recently, I’ve wet my beak a little with Android development, out of curiosity, and so my mission tonight was to take the layout I’d been working on and get it to, you know, actually do something. So, the simplest thing for me to do was have the app reproduce the POST request sent by the browsers to get the desired result. Here is the code I slapped together for this:

final Button myButton = (Button) findViewById(R.id.breakfastNookButton);
        myButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	
            	HttpClient myClient = new DefaultHttpClient();
                HttpPost myPost = new HttpPost("you-get-the-idea");

                try {
                	myClient.execute(myPost);                  

                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

Not the prettiest thing I’ve ever written, but this is a throw-away prototype to prove the concept (though I’m going to refactor tomorrow – I can’t help myself, prototype or not).

So, I fired it up and nothing happened. I checked out the stack trace and was getting an UnknownHostExeption, which didn’t make sense to me, since I was using the home automation server’s IP address. I used the browser on my phone, and I could turn the light off. I googled around a bit and found a bunch of information about things that can go wrong with the emulator, but I’m debugging right on my phone since the Emulator is painfully slow.

Finally, I stumbled across a suggestion and got it right through some experimentation. I needed to give the app permission to use the internet! So, I updated my manifest to the following:



     
    
...

Important line is the “uses-permissions” node, and, viola, let there be dark! My light turned off. Hope that helps someone out there struggling to understand the UnknownHostException for a known host.

(Note, the node level in the XML file is important — it must be a child of manifest, NOT application).