Posts Tagged ‘Javascript’

Using Javascript to control the Nintendo Wii

Monday, August 15th, 2011

The Nintendo Wii was released around the end of 2006. That’s a solid four years now; an amazing amount of time in the lifespan of a technological device these days. Often overlooked is the fact that the Wii has a web browser, which is in fact a build of Opera, offering support for canvas, CSS3, and more advanced aspects of HTML5. This should be incredible; why does nobody develop more for it?

The Ugly Truth

The chief portion is the target market; with so many internet enabled devices laying around these days, the Wii’s browsing experience is one that tends to fall a little short. This was further compounded by a small incident wherein, once the Wii’s browser was released, an article went up on Opera’s official website about responding to Wii remote commands in Javascript – Nintendo later demanded that they take it down, and to this date I’ve never seen any official reasoning put forth by either company.

With that said, I don’t think the Wii (and the browser therein) are 100% lost potential. One of my goals in life is to examine and improve the methods with which we teach programming to children, and I believe the Wii can work very well for these purposes. Typically, young children don’t have their own computers, and from what I’ve found the recurring issue here is that when they’re using their parents computers, they don’t have creative freedom to do something that carries with it the idea of being possibly “destructive”.

The Wii, on the other hand, is generally thought of as the “kids” device – it has a limited set of functionality that kids grasp pretty well right off the bat, and coupled with the concept of “ownership” they’d get out of this device it stands to reason they’re more likely to experiment on it.

There used to be various Wii javascript libraries/SDKs laying around, but most of them are woefully incomplete or no longer available. So with that all in mind, I set out to build a library that allows simple, easy, event-based interaction with the Wii’s browser, hiding away the somewhat insane complexities of reading the remote codes.

Enter: wii-js

You can check out wii-js over on GitHub; it’s entirely open source and released under an MIT-style license. While the repository has in-depth documentation of library usage, check out the example below and see how simple this has become:

This example showcases how to set up basic controller instances, and respond to events that they fire. Most button combinations are supported (check the docs on GitHub for up-to-date event listings), but sadly this library can only work with the actual Wii-remote. Nintendo (or Opera, it’s unknown who) opted not to provide controller mappings for anything else, be it classic controllers or Gamecube controllers. All Wii remote instances, with the exception of the first one, can get controller events from the nunchuk; there doesn’t appear to be a way around this, which is nothing short of a shame.

That said, even with these limitations, it remains a pretty versatile library. The next steps for it are bundling in some basic sound/game engine support to make it even easier for kids to jump in and create. Follow the project on GitHub to see updates!

A Note About Performance

Sadly, the Wii isn’t the most performant device. It has significantly less memory than most devices on the market today; due to this, it’s possible to get under-performant pretty quickly. While it does support the canvas element, it appears you can’t force a repaint any faster than in 100ms intervals – anything lower and the Wii begins to choke repeatedly. This isn’t really fast enough for games; canvas may be useful for other techniques, but for the most part any game engine that’s done outside of Flash needs to be using HTML or SVG. SVG seems promising in recent tests, and it has a side benefit of reacting to DOM events like HTML based scenarios do.

Opera on the Wii also appears to have some level of support for Server-Sent Events, which could possibly prove useful for enabling lightweight two player interaction. The performance considerations here are currently unknown at this time.

The Future

Nintendo recently announced their new console, the Wii U. Whether it will keep the Opera web browser is anyone’s guess; it’s worth noting that the new 3DS replaced the Opera browser used on previous DS incarnations with an engine similar to that of the PSP. There aren’t too many usage metrics which we can use to draw predictions from, either, so at the moment it’s a bit of “wait and see”.

I’m going to continue developing the library and concepts surrounding it during my free time, and ideally want to try teaching a small class or two once I’ve further refined it. If you’re interested in helping out, fork away on GitHub!

Emitting Custom Events in Node.js

Saturday, April 16th, 2011
Note: This is an article I wrote for the March 2011th issue of JSMag. It’s a great piece of literature released monthly, and a great way to keep up to date on the latest news in the Javascript community. Check it out!

Node isn’t the first approach to event based programming, and with its explosion of interest it probably won’t be the last. Typical JavaScript patterns for callback functions involve passing around references to functions and managing odd scope levels. In many cases this is less than ideal; that said, there’s another option when you’re in Node: emit your own events, and let functions attach and respond to those. EventEmitter makes this incredibly easy!

The Typical Approach…

If you’ve written or even worked with JavaScript libraries before, you probably understand the callback function scenario – that is, functions that execute once a certain task is completed. A typical use might be something like what you see in the following example:

Here, we’ve defined a function that accepts another function as its main argument and passes the callback function a doubled version of x. Pretty simple, and many libraries use this technique for Ajax calls. Let’s take a minute and spin the globe, though – what if, instead of arbitrarily accepting a function and having to worry about possible scoping issues, we could just announce when an event of interest has occurred, and fire an attached function at that point? This would be so much cleaner than passing around function references everywhere.

Enter: events.EventEmitter

The great thing about all this? We can actually do this in Node through use of the events library. This, in many ways, is core to how things in Node work. Everything is event based, so why shouldn’t we be able to fire off our own events? To showcase what’s possible with this, let’s build a basic library to connect to Twitter’s Streaming API, which we can then filter results from as we see fit.

The Basics: exporting an EventEmitter instance

Before we get into anything Twitter-specific, we’ll demonstrate basic usage of EventEmitter. The code below shows how simple this can really be – it’s a contrived example that constantly increases numbers by one, and emits an event called “even” every time the number becomes even.

Usage of EventEmitter is pretty simple – you basically want to inherit all the properties from EventEmitter itself into your Object, giving it all the properties it needs to emit events on its own. Events are sent off as keywords (‘even’, ‘error’, etc), called directly on the object. You can extend the prototype chain further, and EventEmitter should work fine and dandy.

Changing Tracks for a Moment…

Now that we’ve shown how EventEmitter works, we want to go ahead and use it for Twitter’s Streaming API. For the unfamiliar, the Streaming API is essentially a never ending flood of tweets. You open a connection, and you keep it open; data is pushed to you, reversing the typical model of “request/response” a bit in that you only really make one request. EventEmitter is perfect for this task, but to satisfy some basic needs for interacting with Twitter’s API, we’ll need a base library, like what’s shown in the example below:

Here we require the three main resources we’ll need (util, http and events), and set up a new Object that’s essentially an instance of EventEmitter. We’ll throw it over to exports, too, so it plays nicely when relying on it in outside code. Creating instances of our Twitter object requires a few things – ‘track’, which is a keyword to filter tweets by, and a ‘username’/’password’ combination which should be self explanatory (in terms of what they are).

Why ‘username/password’, though? Twitter’s Streaming API requires some form of authentication; for the sake of brevity in this article, we’re going to rely on Basic Authentication, but moving forward it’s recommended that you use OAuth for authenticating with Twitter, as it relies on the user granting you privileges instead of actually handing over their password. The OAuth ritual is much longer and more intricate to pull off, though, and would push the length and scope of this article far beyond its intentions.

Emitting a “Tweet” Event

Now that we’ve got the basic scaffolding for our library set up, let’s throw in a function to actually connect, receive tweets, and emit an event or two that other code can catch. Check out the following for a prime example of how we can do this:

If you’ve worked with Node before, this code shouldn’t be too daunting, but we’ll summarize it just in case. We’re extending the prototype of our Twitter object that we created before, and adding a method to start the stream of tweets coming in. We set up an object detailing the host, port, path and method, as well as some custom headers (notably, setting ‘keep-alive’ and Basic Authentication headers). This is passed to an http.request() call, and we then write our tracking data and end the connection.

The response function has some logic to handle putting together tweets that are sent in by Twitter. The API dictates that a tweet object will end on the two characters ‘\r’ and ‘\n’, so we basically walk the built up JSON strings as they come in and separate them out. If a JSON string is successfully pulled out, we emit a ‘tweet’ event, and pass it the parsed JSON data. If something went horribly wrong, we emit an ‘error’ event and pass it the associated object.

Usage and Application

Alright, so now we should have a pretty functional library once we put those two together. The code below shows how we can now use this library in a simple script.

Wrapping Things Up

EventEmitter is an excellent, easy to implement option for dealing with cases where you might want to defer an action until data is ready. Readers with further questions should check out the Node.js documentation on EventEmitter. The source code for this article is included in the full, zipped up magazine download, as well as mirrored at the following link.

Quit incorrectly passing functions in Javascript

Wednesday, June 9th, 2010

In my line of work, I edit a lot of legacy code, and with that I see a lot of the following:

That little piece of code is actually a really bad way of doing things, and (to me) is illustrative of when someone is working in Javascript and doesn’t actually know what they’re doing.

For those who don’t know (and would like to learn), setTimeout (and its sister, setInterval) can accept a string of code to be executed as an argument. Know what other method takes a string of code and executes it? eval() does. Generally, methods like these should be avoided, as they leave ways for arbitrary scripts to run if you’re not careful.

So how could the above code be improved? Take the following:

What’s important to remember here is that *everything* in Javascript is an object. This may seem like grade school material, but it’s surprising how many people miss it – since our function (foo) is an object, we can point to it like any other object. What we’re essentially doing now is, instead of telling setTimeout “hey, evaluate this script after this timer expires”, just “run this function when this timer expires”. There’s no need to invoke eval() for such a simple operation.

But what about my arguments?

Yes, you can still pass arguments with this form. Whereas before you’d make up a whole string to be executed, you’d now just run it with an anonymous function. For those of you using jQuery, this should feel very familiar:

Javascript is incredibly flexible. If you’re going to work in it, take the time to actually understand what’s going on. You (and your users) will be better off for it.

jQuery Introduction, Refresh Fred May 2010

Thursday, May 13th, 2010

I had the awesome chance to give a presentation at the May 2010 meeting of Refresh Fred. The talk I gave was on an introduction to jQuery (as well as some basic Javascript).

The great part is that, since I opted to build the presentation in HTML, CSS, and JS, it’s easily viewable online. You can check out the presentation online, or check out the source on Github.

The entire presentation is MIT licensed (of course, that goes as far as a presentation even so much as *can* be licensed). Feel free to take the code, remix it, extend it, or re-use it – go crazy and enjoy.