Tuesday, March 8, 2011

Android TV Remote

TV remotes are simple devices. All that it takes to make one is an IR emitting diode and a small amount of logic to make the diode blink at the right intervals for the TV to interpret.
The total cost of the materials involved in the construction of such a device is small, probably 5$ at the most. I recently bought a TV remote from Radio Shack and took it apart to confirm the components involved. The device was nearly entirely molded plastic and buttons, plus the one IR diode and the one small chip to control it.

Now, I'm a very lazy person, as this blog post clearly demonstrates, so instead of keeping track of many small fist sized electronic devices that are involved with remote communications, I only want to keep track of only one -- my phone.
This would be a wonderful brilliant solution and a major selling point for whatever phone had incorporated the 5 dollars worth of parts required to make this work, but alas, I know of no phone that currently incorporates an IR LED.
>:P

But my laziness will not be denied, so after a bit of searching on the interwebs, I found a company called global cache which makes devices that facilitate laziness. Particularly ethernet connected IR emitters. So my solution begins to look like this:
Brilliant! Except that is not what I'm going to do. For one thing I opted for a GC-100 which is wired, not wireless. It also connects a relay, a serial, and 3 IR ports via TCP/IP. One of the IR ports has to be used to connect an IR Blaster which actually emits the IR signal.
Brilliant! But android-java is not my forte. So I made a solution that looks like this:
Well, I've removed the whole point of this exercise, which is to control the TV from my phone, but I'll add that back in later. In the meantime, the powershell script is exactly what I want to prototype the application and test that this much, at least, does work.

$msgOnOff = "sendir,2:1,1,37000,1,1,333,167,21,20,21,20,21,61,21,20,21,20,21,20,21,20,21,20,21,61,21,20,21,20,21,61,21,61,21,61,21,20,21,61,21,20,21,20,21,20,21,20,21,20,21,20,21,20,21,20,21,61,21,61,21,61,21,61,21,61,21,61,21,61,21,61,21,1576,333,83,21,740" + [char]::ConvertFromUtf32(13)
$msgMute = "sendir,2:1,1,37000,1,1,333,166,21,20,21,20,21,62,21,20,21,20,21,20,21,20,21,20,21,62,21,20,21,20,21,62,21,62,21,62,21,20,21,62,21,20,21,62,21,20,21,62,21,62,21,20,21,20,21,20,21,62,21,20,21,62,21,20,21,20,21,62,21,62,21,62,21,1572,333,84,21,740" + [char]::ConvertFromUtf32(13)
$msg = $msgOnOff
$ipaddress = [System.Net.IPAddress]::Parse("192.168.1.70")
$ipendpoint = New-Object System.Net.IPEndPoint -ArgumentList $ipaddress, 4998
$addressFamily = [System.Net.Sockets.AddressFamily]::InterNetwork
$socketType = [System.Net.Sockets.SocketType]::Stream
$protocolType = [System.Net.Sockets.ProtocolType]::Tcp
$socket = New-Object System.Net.Sockets.Socket -ArgumentList $addressFamily, $socketType, $protocolType
$socket.Connect($ipaddress, 4998)
$bytes = [System.Text.ASCIIEncoding]::ASCII.GetBytes($msg)
#$bytes
$socket.Send($bytes)
$socket.Close()

Running this script enabled me to turn the TV on and off programmatically, proving that I had the hardware set up right and that the whole concept would work. The strings: $msgOnOff and $msgMute were taken from using an IR learner and Global Cache's eLearn software.  It took me a bit of fiddling to get the  [char]::ConvertFromUtf32(13) at the end of the strings figured out, and until I did, the script did not work. 


So the next thing that I did was set up a web service that would launch the powershell script. This would enable me to test the set up with a simple web page. That solution looked something like this: 

The web service code looks like this: 


1 [OperationContract]
2 [WebGet]
3 public void ToggleMute()
4 {
5     ProcessStartInfo info = new ProcessStartInfo("powershell.exe");
6     info.Arguments = "-f \"C:\\LivingRoom\\sendirMute.ps1\"";
7     info.RedirectStandardError = true;
8     info.RedirectStandardOutput = true;
9
10     info.UseShellExecute = false;
11
12     System.Diagnostics.Process process = Process.Start( info);
13     return;
14 }

 That code runs a bit slow, so there's about a one second delay between when you launch that code and the TV actually turns off (or mutes itself in this case). I'll have to revisit this in the future and see if I can get it to run more quickly using runspaces or some other trick. 


And then there's the ajax that I use to call the web service: 

    function OnOff() {
        $.ajax({
            url: 'LivingRoom.svc/ToggleOn',
            type: "GET",
            cache: false
        });
    }


Once I verified that this worked from a browser, I was able to publish the website to my local server, and browse to it with my phone's browser, and click on the button that I put on the web page and I finally had my phone operating as a TV remote. 

At this point, the solution works with any device that has a browser (blackberry, iphone, android, random laptop). I could use windows scheduler to toggle the mute or on/off at any time (though I don't know how that would be useful). But what I really want it a native android application that is the User Interface, and not a web page, so after creation of an Android App the solution looks like this: 


public class NotesList extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final Button button = (Button) findViewById(R.id.Button01);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                HttpGet httpGet = new HttpGet("http://192.168.1.76/LivingRoom/LivingRoom.svc/ToggleMute");
                try {
                    httpClient.execute(httpGet, localContext);
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }
}


So I've created an Android based TV remote, woot. 

Here's a list of some of the technologies and programs that I used in this little exercise:
Powershell
IIS
aspnet_regiis.exe
Visual Studio 2010
Javascript/JQuery/Ajax
C# Web Service
Eclipse
Windows 7 
Ubuntu Linux
Android Java
Enterprise Architect (for the diagrams)
Paint (for prepping the diagrams)

Monday, February 28, 2011

Fun with HTML 5

Flash had to make up the difference between what I wanted to do on a web page and what I could do before HTML 5 for two things:
1) Playing sound.
2) Drawing on a canvas.

I had the sound working with flash using a small utility called sound manager. It was a pain, difficult to get working and keep working, but it did work in the end. However, the HTML 5 audio tag makes things easy and straightforward. For example:


1 <audio controls="controls" src="http://www.ogresoft.com/Japanese/TortoiseSVN_error.ogg" tabindex="0">
2 Your browser does not support the audio element.
3 </audio>





 If your browser doesn't support HTML 5, then go download a new one.

I never got the drawing canvas working. I considered processingjs, but HTML 5 came along before I got bored enough to make it work.

Ogresoft Kanji Quiz

So you can draw the kanji for the specified English word, instead of just a multiple choice scenario. I'll trust you to grade yourself correctly.

But my stuff is boring and rudimentary. Here are a couple of sites that do it right with canvases and drawing:
Harmony
and
Sketchpad
and here's another:

http://juliamap.googlelabs.com/

Monday, February 14, 2011

Stuff that I only use once every 6 months: XPath

It became convenient to manipulate some XML inside of a field in Sql Server (2008 r2) recently.
I found the XML datatype and the modify function which operates using XQuery. XQuery is a superset of XPath and both are w3c standards.
The silly field wasn't the XML data type already, it was just an nchar stuffed full of Xml.
The query that I wrote looked something like this when I was done:

1 CREATE TABLE T(TheXml XML)
2 GO
3
4 INSERT T SELECT CAST(code as XML) FROM some_table WHERE name = 'that thing that I was looking for'
5 GO
6
7 UPDATE T SET TheXml.Modify('delete /Object/Object/Object[@name="That one name"]/../Object')
8 GO
9
10 DROP TABLE T
11 GO

Most of my time was spent in the act of realizing that I needed to look for help on XPath and not some weird microsoft thing. The syntax that I needed (in this case "..") was easily found once I googled XPath.

Saturday, February 5, 2011

World of Warcraft automation using powershell

I have some crafting that I do in World of Warcraft that is repetitive, lucrative, and boring. If I sit at the keyboard doing it, I'm essentially just executing a for loop in my head. Not my idea of fun, especially when it could be an opportunity to hone my 'leet programming skills.

I used to automate this activity with AutoHotKey (AHK). It worked great, however, it was a new pseudo-programming language that I had to learn, and a very specific one at that. I've done some neat things with AutoHotKey, but I would prefer to use something like powershell instead. Powershell has the advantage that it can be used in a much broader set of domains than AutoHotKey, and therefor more likely to be useful to me in the future for some as of yet unknown task. I had toyed with the idea of embedding AHK inside of powershell and executing AHK commands within a powershell script, but I have found a better solution.

Up until .net 4.0 I had considered making AHK commands embeddable in Powershell. But! .net 4.0 brings us the System.Windows.Automation namespace.

With this small bit of knowledge, I was able to craft the following sample:


Import-Module C:\Windows\Microsoft.NET\Framework64\v4.0.30319\WPF\UIAutomationClient.dll
$a  = [System.Windows.Automation.AutomationElement]::RootElement.FindAll([System.Windows.Automation.TreeScope]::Descendants, [System.Windows.Automation.Condition]::TrueCondition)
$wow = $a | Where { $_.Current.Name -eq "World of Warcraft" }
$pattern = $wow.GetCurrentPattern([System.Windows.Automation.WindowPattern]::Pattern)
$pattern.SetWindowVisualState([System.Windows.Automation.WindowVisualState]::Normal)
[System.Windows.Forms.SendKeys]::SendWait("{Enter}Hi{Enter}")

Making my character say "Hi", isn't terribly useful, but it illustrates how I could send any sort of command at all to Wow.

This uses .Net 4.0 which screws up in most default configurations of powershell and powershell editors. In order to configure your powershell environment to run on .net 4.0 and be able to run this script, add the following configuration file to your editor of choice.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0.30319" />
</startup>
</configuration>

A more thorough discussion of .net 4.0 and powershell.

That config file wasn't working with PowerGUI though. I had to resort to the registry keys:

New-ItemProperty -Name "OnlyUseLatestCLR" -Value 1 -Path "HKLM:\software\wow6432node\microsoft\.netframework\"
New-ItemProperty -Name "OnlyUseLatestCLR" -Value 1 -Path "HKLM:\software\microsoft\.netframework\"

Sunday, January 30, 2011

Android TV Remote - Failure one

, I decided my phone should also act like a TV remote. The first problem with that is the missing hardware. It doesn't have an IR emitter. After a brief search, I decided that Android Phone - IR Emitter integration didn't exist, and I proceeded to begin building my own.

 My first attempt was to buy a 20$ universal remote from radio shack and attempt to wire up the buttons so that I could invoke them digitally. I took apart the remote and discovered that it was essentially a single board with an IR emitter at the front. I glued wires to the button contacts and glued the wires to the board with hot melt glue so that the fragile wire-glue connections would not break.

I connected the wires to a breadboard and could push the buttons electronically with the digital out from an arduino. I could then hook the arduino up to a webservice and I would have the first iteration of a working android/web phone remote.

 But! Then I saw this product from Global-Cache GC-100. It allows serial, IR, and other devices to be hooked up to an ethernet network and accessed remotely. So, although wiring up a TV remote to an arduino was fun, challenging, and a useful trick to have in my arsenal, it also wasn't better than the existing commercial solution. I have abandoned this avenue of attack and ordered a GC-100.

Monday, December 6, 2010

Virtualization

I don't want to use Hyper-V because it requires a separate machine (unless you're developing on Windows 2008 -- I'm not).
I don't want to use Virtual PC because it doesn't support snapshots.
I don't want to use VMWare player because it doesn't have a good api.
I don't want to use VMWare server because it just plain sucks.
I don't want to use VMWare Workstation because it isn't free.
I am using VirtualBox. It has snapshots. It can be automated with a very rich command line.

For Example:
.\vboxmanage guestcontrol execute [[TheMachineName]] \\vboxsvr\Public\InstallStuff.exe --username [[theUserName]] --password [[thePassword]]

Automatically installs the latest build of the software. InstallStuff.exe is an AutoHotKey script that gets the latest build from a network share then automates the installer. So this automates the deployment of the latest build on a virtual Machine.

Friday, December 3, 2010

WinDbg

I'm posting some notes from my latest debugging adventure.

The big advantage to WinDbg is easy deployment on a test machine. I don't have to worry about installing remote debugging with visual studio or correctly setting up the permissions.

The notes:

1) Although the download site says that you probably want to run 64 bit WinDbg on a 64 bit machine, the machine architecture is irrelevant. Most apps that I've been writing, and especially those that use legacy COM objects are x86 and WinDbg behaves poorly if you don't get the right version for your architecture. The download page is here.

2) Downloading WinDbg is still annoying. But this is only because I remember the good old days where I only needed to download the Debugging Tools for Windows and not some entire SDK.

3) sxe clr
This breaks the debugger whenever there is a CLR exception. I'm always after some .net bug. This is the first thing that I type in to get going, usually right after WinDbg attaches.

4) .loadby sos mscorwks
This loads the SoS Debugging extensions for .net. I wait until WinDbg breaks after the first CLR error, because this command won't work until mscorwks is actually loaded by the program.

5) !pe
This is short for !PrintException. It outputs information about a .net exception.

6) !CLRStack
This outputs the .net stack trace, ignoring the surrounding native code.

7) !dso
Dump Stack Objects. Helps you figure out what objects in memory are likely to be involved in any current problem.

8) !do
Dump Object. Information about a single object.

A cheatsheet