There’s Nothing Wrong With Failing

Fail!

Failure to Communicate

So this post will be pretty short, but I wanted to quickly touch on a workplace experience that happened the other day. I was approached by a colleague (who’s perspective I really value) about the way some of us on the team were discussing a series of events. This individual was really concerned that we kept calling it a failure, and in this person’s mind, we hadn’t truly failed at anything. We had done an experiment in terms of tackling a development problem and the team had reached a critical mass where we declared “enough is enough, this is a failure”. I became concerned because I wanted to make sure this person and I were on the same page.

I couldn’t totally wrap my ahead around why this person was so concerned about calling it a failure. In my opinion, all the evidence was there to call it a failure! But I guess that was just a failure on my part to communicate properly. I think that there was a work culture gap where this person was viewing our declaration of a failure as something really negative, whereas a lot of us were really just marking it as a point of realization to not continue along with something. All of the reasons this person offered up for why our experiment was not a failure were true. We hadn’t missed a deadline to ship and we had a plan for how to work around it. That sounds like success, right?

I guess the communication breakdown was really this: There’s nothing wrong with failing. We tried something and we’ve identified that it’s not working. That’s a failure. What makes us successful? Being able to identify our failures, learn from them, and improve going forward. And that’s exactly what we’re doing. Acknowledging a failure and planning how we can be better next time around.

So with that said… You should be failing when you push the boundaries. Just make sure you learn from your failures.


Multiple C# Projects In Your Unity 3D Solution

Unity

Problem: Visual Studio and Unity Aren’t Playing Nice!

Disclaimer: I develop on Windows, so I have no idea if any of this even applies to other operating systems. I assume not. Sorry.

I just started poking around in Unity 4.6 and I’ve been having a blast. I’ve made it to the point where I want to actually start hammering out some code, but I came across a bit of a problem: I want to start leveraging other projects I’ve written in my Unity solution while I’m in Visual Studio, and things are blowing up. So, what gives?

Okay, so let me start by explaining why I want to do this. I understand that if I’m making a simple game, I should have no problem breaking out my unity scripts into sub folders and organizing them to be nice and pretty. The problem I’m encountering is that I have existing projects under source control and I don’t want to copy and paste all of the code as scripts into my Unity folder. I also want to be able to create re-usable code for my future games, so I’d like to start breaking things out into libraries as I see fit.

So, if you’ve been playing around in Unity for a bit, you might say “Oh, well you’re a dummy! Unity can totally leverage your C# DLLs once you drop them into your asset folder”! And you’d be 100% correct. But that’s not the workflow I want.

The underlying problem here is this: Unity will re-write your solution and project file when you flip between Unity and Visual Studio. But I’m sure they have it that way for a reason.

The Goal: Visual Studio and Unity Should… Play Nice!

My ideal state would be something like this:

  • Work in visual studio as much as I’d like to new projects to my solution, and reference them accordingly
  • Flip back and forth from Unity and Visual Studio without having to reset things to compile/run again
  • Build from visual studio and have things end up in the right spot… NOT copy DLLs
  • Not copy+paste my entire project(s) already under source control elsewhere

Is this something that can be achieved though? I was pretty determined that I should be able to do *something* to have this working. Could I get it perfect? I wasn’t sure… But I knew I could make it better.

The Solution: Give and Take with Unity

My *almost* perfect sution, which I’ll walk you through, is this: Leveraging Visual Studio tools for Unity, modify the Unity solution as you see fit and use directory junctions (symlinks) to the build output directories of other projects.

  1. Let’s get Visual Studio tools for Unity installed. Visit that link and download the version that you need for the version of Visual Studio that you use. After installing, I opened up my project within Unity and I had to import the Visual Studio Tools package.Import Package
    After selecting this menu item, I was presented with a dialog for picking the items to import. I left it as is.Import Package2After importing these items, I could see that Unity had successfully added these entries under my Assets folder. Okay, now we’re getting somewhere. Next up, I wanted to configure Unity to not modify my solution every time I go back and forth from Unity to Visual Studio. This is the part that kills whether or not I’ve added projects to my solution. For me, it’s critical to have code I’m working on immediately accessible so that I can jump back and forth between projects. Lucky for us, this part is pretty easy. Go to the menu to access your new Visual Studio Tools menu item:

    VS Tools Configure
    Selecting “Configuration” opens up a really simple dialog. Let’s make sure “Generate solution file” is unchecked! It’s that easy.

    VS Tools Configure2
    Once we have all of this setup, we should be able to go into Visual Studio and add other projects to our solution.

  2. The one thing that I *could not* get this solution to do is have Unity leave my main game project alone in Visual Studio. As a result, the rest of this walk through is allowing us to play by Unity’s rules. Unity is good at magically referencing all of the managed DLLs that you include within your assets folder. If you drop DLLs somewhere within “Assets” and switch to Visual Studio, Unity will likely have modified your main project to reference this DLL.My next step was creating a spot where I wanted to drop the build outputs of my extra projects I wanted to reference. In my Visual Studio solution, I have my original game project and some newly added projects I want to build from source. In Unity, I wanted these to end up in “Assets/Dependencies/bin”. No problem. Let’s make that folder structure (or your equivalent if you don’t like my naming):Bin Dependencies
    The next part is probably the “trickiest” part because it’s… well… unusual. You could technically stop here and manually copy DLLs back and forth, but I’m not about that life. I want things to happen automatically. For this, we’re going to use junction points. Browse to your newly created folder in an administrator command prompt. I say administrator because only certain users have permissions to create junction points. Your non-admin user might, but this is my “safe” way of instructing you. On the command prompt, we’re going to use “mklink” to create a junction. The command is “mlkink /D /J <NAME_OF_YOUR_PROJECT> <RELATIVE_PATH_TO_YOUR_PROJECT>”. For example, if you had a C# project you wanted to reference that was “MyCoolLibrary.csproj” and was located in the directory above your Unity project, you might use the command “mlkink /D /J MyCoolLibrary “……..MyCoolLibrarybindebug””. Note that I used two dots to go back up a directory several times (since we’re inside of AssetsDependenciesbin and want to get outside of our Unity project). you should get a success message when your junction is created.

    Repeat this step for as many extra projects as you want to include. You can always come back and add more projects this way too, or remove the junctions if you don’t want to include a project anymore.

    At this point, you’re technically done. If you build from Visual Studio, you should have your other projects’ DLLs end up in your Unity folder, and your main game project will be updated by Unity to reference these now!

  3. But… You’re not done if you use source control for your Unity project and have separate source control on your other projects. The scary thing here is that usually we don’t want our build outputs to be stored in source control… But if we do nothing else, your source control system will likely want to include the newly created “AssetsDependenciesbin” folder and any of the contents you’re building into there. I just modified my git ignore file (I’m sure there’s an equivalent for SVN or other source control) to exclude the contents of “AssetsDependenciesbin”.The reason I didn’t excluded dependencies all together is because I can add other folders and DLL references here that I don’t want to build (like… the normal way). This gives me the flexibility of building the projects I want to control and still be able to just reference other pre-built DLLs!

Summary

In three easy steps, you should be able to use Unity, Visual Studio, and multiple projects in one solution in a what-feels-like-normal way. Because there’s still some dynamic stuff going on with Unity updating your main project, you might find the odd time you need to build twice to fix up compilation problems. I’ve seen this happen maybe once or twice so far, but otherwise it feels like normal. It’s also  important to note that you can’t escape the Unity project updating… don’t add references to your main project manually. That’s what that “AssetsDependencies” folder is for that we made.

Here are a few shots of what my setup looks like (proof that it works):

Solution Explorer

Unity Dependencies

And of course… it’s not the perfect solution. There’s still these things:

  • Unity gets mad at you for using junctions within your project. It actually tells you not to do this because you can mess things up. It’s working awesome for me right now though… So I’m going to just ignore this warning.
  • Remember step 3 where we ignored the AssetsDependenciesbin location in git? This actually ignored your junction points you created too. As a result, anyone else who clones your code will need to create junctions too. I’m working solo, so I’m not too worried about this step… But it’s definitely something that should be fixed up (again, I’m sure it’s doable, but I’m in no rush).

Hope that helps you feel more at home in Unity and Visual Studio! It certainly made it nicer for me.

 


C# Dev Connect 1 – Intro To Threading

C# Dev Connect

C# Dev Connect 1: Intro to Threading

In my last post, I mentioned we’d be hosting a C# Dev Connect meetup at our Magnet Forensics HQ in Waterloo. I figured I’d post to talk about how the event went so that if you couldn’t make it, you’ll have an idea for next time (and if you did make it, maybe you can comment on how you thought the event went). Our first Dev Connect was lead by a colleague of mine, Chris Sippel, who wanted to give a talk on threading basics in C#. Threading can quickly become a really complex topic, so Chris wanted to keep it high level and talk about the different approaches you can use to start threading in your C# applications.

Dev Connect: Before the Talk

Before Chris gave his talk on threading, we had our attendees slowly streaming in. Sure, we had a lot of our Magnet development team show up to offer support for Chris, but I was still pleasantly surprised to see others from the area that I’ve never met before showing an interest in C#. Our colleague Amaris had done an awesome job coordinating the first event for us, and even got us stocked up with pizza and pop. For the first hour or so, we had our guests fed and introduced to each other. A great start to the evening!

Dev Connect: The Talk

After everyone was settled in, we had our attendees pull up some chairs at tables or post up in our comfy soft seating to listen to what Chris had to say. Chris walked us through various slides and coding examples and was able to show us working examples of code to back up what he was saying. I was really proud of Chris for taking the leap to be our first speaker, and I think he did a great job. His slides and sample code are available at the Dev Connect git hub if you’re interested in taking a peek.

Dev Connect: The Aftermath

Once Chris was done talking, we had a few attendees leave to carry on with the rest of their evening, but it was great to see the majority hang back for further discussion. Some people were trying out the threading exercises that Chris had put together, others had tried it beforehand and had questions on it, and a bunch of people were sticking around just to talk .NET. When I envisioned what Dev Connect might have looked like, this was it. It felt great to help facilitate a positive discussion around using the .NET framework and C#, especially because people were clearly benefiting from it.

If you came for our first meetup, then thanks! If you couldn’t make it or you’re interested in the next one, be sure to check out our meetup page. We’ll see you next time!


First C# Dev Connect is Coming Up

C# Dev Connect

 

C# Dev Connect Meetup!

About a year ago I had thrown around the idea of creating a C#-specific group that would meet at a regular interval with some of my colleagues. I saw that there was interest, but between all of the things we had going on in our personal lives and work lives, we just hadn’t been able to co-ordinate something. I’m excited to announce that with some more solid planning over the last couple of months, C# Dev Connect will be able to host their first meetup! The company I work for, Magnet Forensics, has graciously offered our new office to host the event which will help tremendously. We’ll have a group of people from Magnet Forensics their to help out, but the only thing “Magnet” about the event is really just that it’s hosted at the office.

What’s on the Dev Connect Agenda?

This upcoming Tuesday (Tuesday January 20th, 2015) C# Dev Connect will be hosting their first monthly meetup on the topic of Threading in C#. Directly from the event’s Meetup page:

Overview of the the basics of threading in C# language. Threading is a very complex idea with many different ways of handling the same problem, however, you have to learn to crawl before you can walk. We’ll be discussing the basics of threads in .NET 2.0 and .NET 4.0. In .NET 2.0 we’ll be discussing the Thread object, various ways to start/stop threads, and potential stumbling blocks when it comes to threading in C#. In .NET 4.0 we’ll be talking about the async and await operators and how to use them.

A colleague of mine, Chris Sippel, will be giving the talk. People are encouraged to bring their laptops so they can try out some C# exercises related to the discussion. This initial talk may be more geared at an introductory-level, but our goal is to be able to cover topics for all levels of knowledge in C# (From never used it before, to expert level). We’ll even provide some food! All you have to do is show up and be ready to learn some C#, or share your C# knowledge.

If you’re looking for our venue, we had this little map put together:

C# Dev Connect Venue Map

Go into the back of 156 Columbia Street West in Waterloo (at the corner of Phillip and Columbia). If you’re familiar with the area, this used to be called RIM/Blackberry 5.

 

More Dev Connect Info

Here are a few additional links to get you to more C# Dev Connect information online:

We’re excited for you to join us!


MyoSharp – Update On The Horizon

MyoSharp

If you haven’t checked it out already, my friend Tayfun and I created an open source C# wrapper for Thalmic’s Myo. It’s hosted on GitHub over here, so you can browse and pull down code whenever you want. We’ve had some great feedback from users of our API, so we continue to welcome it (both positive and negative!) in order to improve the usability.

Thalmic has plans to release a firmware update to allow more data to be accessible through their API. Right now, MyoSharp is a bit out of date, but once this big firmware update lands we’ll take some more time to get it up to date again. Remember, it’s open source so you can feel free to contribute!

Troubleshooting

The most common question I receive is “I keep getting an exception about not being able to connect when I run the sample code”. I’ve tried to help a few people through this so I just figured I’d mention it right here for clarity: It’s more than likely that your MyoConnect version and the version we packaged with MyoSharp have become out of date. You probably keep your Myo SDK more up to date than MyoSharp is.

Don’t worry! So far we’ve had reasonably good luck just replacing the Myo DLLs in the x86 and x64 folder of the solution. Provided Thalmic didn’t break any API compatibility, things should actually just work out of the box. If they *DID* break backwards compatibility, it’s likely not that big of a deal either. You can update the PInvokes used to match the signatures they expect, and again, you should be up and running pretty quickly.

With that said, hold tight! We’ll get something updated soon. If you can’t wait, then that’s my suggestion for how to get up and running. Please don’t hesitate to contact Tayfun or myself for troubleshooting. Just post in the comments here and we can try to help out!


ProjectXyz: Enforcing Interfaces (Part 2)

Enforcing Interfaces

This is my second installment of the series related to my small side project that I started. I mentioned in the first post that one of the things I wanted to try out with this project is coding by interfaces. There’s an article over at CodeProject that I once read (I’m struggling to dig it up now, arrrrrghh) that really gave me a different perspective about using interfaces when I program. Ever since then I’ve been a changed man. Seriously.

The main message behind the article was along the lines of: Have your classes implement your interface, and to be certain nobody is going to come by and muck around with your class’s API, make sure they can’t knowingly make an instance of the class. One of the easiest ways to do this (and bear with me here, I’m not claiming this is right or wrong) is to have a hidden (private or protected) constructor on your class and static methods that let you create new instances of your class. However, the trick here is your static method will return the interface your class implements.

An example of this might look like the following:


public interface IMyInterface
{
    void Xyz();
}

public sealed class MyImplementation : IMyInterface
{
    // we hid the constructor from the outside!
    private MyImplementation()
    {
    }

    public static IMyInterface Create()
    {
        return new MyImplementation();
    }

    public void Xyz()
    {
        // do some awesome things here
    }
}

Interesting Benefits

I was pretty intrigued by this article on enforcing interfaces for a few reasons and if you can stick around long enough to read this whole post, I’ll hit the cons/considerations I’ve encountered from actually implementing things this way. These are obviously my opinion, and you can feel free to agree or disagree with me as much as you like.

  • (In theory) it keeps people from coming along and tacking on random methods to my classes. If I have an object hierarchy that I’m creating, having different child classes magically have random public APIs changing independently seems kind of scary. People have a harder time finding ways to abuse this because they aren’t concerned with the concrete implementation, just the interface.
  • Along with the first point, enforcing interfaces makes people think about what they’re doing when they need to change the public API. Now you need to go change the interface. Now you might be affecting X number of implementations. Are you sure?
  • Sets people up nicely to play with IoC and dependency injection. You’re already always working with interfaces because of this, now rolling out something like Moq or Autofac should be easier for you.
  • Methods can be leveraged to do parameter checks BEFORE entering a constructor. Creating IDisposable implementations can be fun when your constructor fails but and your disposable clean up code was expecting things to be initialized (not a terribly strong argument, but I’ve had cases where this makes life easier for me when working with streams).

Enforcing Interfaces in ProjectXyz

I’ve only implemented a small portion of the back-end of ProjectXyz (from what I imagine the scope to be) but it’s enough where I have a couple of layers, some different class/interface hierarchies that interact with each other, and some tests to exercise the API. The following should help explain the current major hierarchies a bit better:

  • Stats are simple structures representing an ID and a value
  • Enchantments are simple structures representing some information about modifying particular stats (slightly more complex than stats)
  • Items are more complex structures that can contain enchantments
  •  Actors are complex structures that:
    • Have collections of stats
    • Have collections of enchantments
    • Have collections of items

Okay, so that’s the high level. There’s obviously a bit more going on with the multi-layered architecture I’m trying out here too (since the hierarchies are repeated in a similar fashion in both layers). However, this is a small but reasonable amount of code to be trying this pattern on.

I have a good handful of classes and associated interfaces that back them. I’ve designed my classes to take in references to interfaces (which, are of course backed by my other classes) and my classes are largely decoupled from implementations of other classes.

Now that I’ve had some time to play with this pattern, what are my initial thoughts? Well, it’s not pure sunshine and rainbows (which I expected) but there are definitely some cool pros I hadn’t considered and definitely some negative side effects that I hadn’t considered either. Stay tuned

(The previous post in this series is here).


ProjectXyz: Why I Started a Side Project (Part 1)

ProjectXyz

Alright, I’ll admit it… Even for a placeholder name on a side project it’s pretty terrible, right? Well, my apologies. So, if you made it to this post you might be wondering what ProjectXyz is and why I started it up. From a high level, I started working on ProjectXyz so that I could have a hobby programming project to tinker with and I figured I’d blog about my adventures in bringing it all together. I plan on making this a mini-series documenting some of the things I’m learning or experimenting with, so this will serve as the intro to the series.

Before we get too far, here’s the link to the GitHub site: https://github.com/ncosentino/ProjectXyz

Why Have a Side Project?

Here’s the main thing I want to talk about in part 1 of this series: Why should you have a side project?

From my experiences in high school and university, I found that having a side project that I could code in was probably the best way that I could continue to learn. It’s a low stress activity that encourages you to be highly creative. You can involve as many other people as you want, or work on it completely solo so that you can minimize external stress and maximize your own creativity. It’s your project, so you have the freedom to do what you want.

I leveraged various small side projects to learn things like how sockets work or how I’d try and structure a multi-tier application. I was able to work on refactoring large amounts of code and learn how to use source control to my advantage. Was there a design pattern I wanted to learn about implementing? Great! Then I could try and find a way to incorporate it into my projects. The goal was always about trying to implement new things and not about cutting corners to try and deliver something to an end user.

Once I started work full-time, I gave up on my programming side projects. I started up this blog which has been fun and I try to take on as much work for my career as I can because I actually enjoy my job… But I stopped coding my own hobby projects. I’ve found that I’m missing out on two major things as a result of that:

  • The ability to experiment with patterns, technologies, and frameworks
  • The ability to get really creative and try out completely new things

Work has been a great opportunity to learn, but it’s learning out of necessity. Myself or my team will hit blocks and we have to work together to try and overcome them. It doesn’t give me the opportunity to go completely into left field to try something new out. Having a side project gives me a bit of freedom to try and learn all sorts of really neat things.

So… Why ProjectXyz?

Okay, well, if you mean why the name… Then I don’t have a great answer. I wanted to start coding but I didn’t want to waste time thinking about a name. I’ll think of something better later, I promise.

Otherwise, you might be wondering why I decided to build ProjectXyz to be what it is (or, what it will be). ProjectXyz is the back end (i.e. not the pretty graphical part) for a role playing game, and I’ve played around with this kind of thing before. I like playing games like this, and I’ve had a lot of fun trying to create a game like this in the past. As a result, I can really focus on what I’m building and not trying to figure out what to build. I’m not pouring energy into wondering “how do I solve this great big popular problem with this piece of software?”, but instead I can just get as creative as I’d like. It’s not about “What does the customer want?”, but instead, I can ask “What do I want to make?”.

The things I’m looking to try out with ProjectXyz (to start with, at least) are:

  • More LINQ usage
  • Coding by interfaces
  • API design
  • Dependency injection and IoC
  • TDD and coded test designs
  • Moq for mocking my classes
  • … GitHub! To make some publicly visible code.

As I work through ProjectXyz, I’ll write more posts on the various things I’m learning as I go! Check out the GitHub page and drop some comments!

https://github.com/ncosentino/ProjectXyz
(The second post in this series is here)


Controlling a Myo Armband with C#

Controlling a Myo Armband with C#

Background

Thalmic Labs has started shipping their Myo armband that allows the wearer’s arm movements and gestures to control different pieces of integrated technology. How cool is that? My friend and I decided we wanted to give one a whirl and see what we could come up with. We’re both C# advocates, so we were a bit taken back when we saw the only C# support in the SDK was made for Unity. We decided to take things into our own hands and open source a Myo C# library. We’re excited to introduce the first version of MyoSharp!

The underlying Myo components are written in C++, and there’s only several functions that are exposed from the library that we can access. In order to do this, we need to leverage platform invocation (PInvokes) from C# to tap into this functionality. Once you have the PInvokes set up you can begin to play around!

The Workflow

Getting setup with the Myo is pretty straightforward, but it wasn’t obvious to us right away. We didn’t have anyone to walk us through how the different components were supposed to work together (just some good ol’ fashioned code) so we had to tinker around. Once we had everything mapped out, it was quite simple though.

  1. The first step is opening a communication channel with the Bluetooth module. You don’t need to worry about the implementation here since it’s all done in C++ by the Thalmic devs. Calling the correct methods using PInvokes from C# allows us to tap into a stream of “events” that come through the Bluetooth module.
  2. Now that we can intercept events, we need to be able to identify a Myo. After all, working with Myos is our main goal here! There’s a “pair” event that we can listen to from the Bluetooth module that notifies us of when a Myo has paired and provides us a handle to the device. This handle gets used for identifying events for a particular Myo or sending a particular Myo messages.
  3. There’s a connect event that will fire when a Myo connects after it’s been paired with the Bluetooth module. A Myo can be paired but disconnected.
  4. Now that we can uniquely identify a Myo, the only things we need to do are intercept events for a particular Myo and make sense of the data coming from the devices! Orientation change? Acceleration change? There’s a host of information that the device sends back, so we need to interpret it.
  5. When a Myo disconnects, there’s an event that’s sent back for that as well.

Getting Started with MyoSharp

I’m going to start this off with some simple code that should illustrate just how easy it is to get started with MyoSharp. I’ll describe what’s going on in the code immediately after.


using System;

using MyoSharp.Device;
using MyoSharp.ConsoleSample.Internal;

namespace MyoSharp.ConsoleSample
{
    /// <summary>
    /// This example will show you the basics for setting up and working with
    /// a Myo using MyoSharp. Primary communication with the device happens
    /// over Bluetooth, but this C# wrapper hooks into the unmanaged Myo SDK to
    /// listen on their "hub". The unmanaged hub feeds us information about
    /// events, so a channel within MyoSharp is responsible for publishing
    /// these events for other C# code to consume. A device listener uses a
    /// channel to listen for pairing events. When a Myo pairs up, a device
    /// listener publishes events for others to listen to. Once we have access
    /// to a channel and a Myo handle (from something like a Pair event), we
    /// can create our own Myo object. With a Myo object, we can do things like
    /// cause it to vibrate or monitor for poses changes.
    /// </summary>
    internal class BasicSetupExample
    {
        #region Methods
        private static void Main(string[] args)
        {
            // create a hub that will manage Myo devices for us
            using (var hub = Hub.Create())
            {
                // listen for when the Myo connects
                hub.MyoConnected += (sender, e) =>
                {
                    Console.WriteLine("Myo {0} has connected!", e.Myo.Handle);
                    e.Myo.Vibrate(VibrationType.Short);
                    e.Myo.PoseChanged += Myo_PoseChanged;
                };

                // listen for when the Myo disconnects
                hub.MyoDisconnected += (sender, e) =>
                {
                    Console.WriteLine("Oh no! It looks like {0} arm Myo has disconnected!", e.Myo.Arm);
                    e.Myo.PoseChanged -= Myo_PoseChanged;
                };

                // wait on user input
                ConsoleHelper.UserInputLoop(hub);
            }
        }
        #endregion

        #region Event Handlers
        private static void Myo_PoseChanged(object sender, PoseEventArgs e)
        {
            Console.WriteLine("{0} arm Myo detected {1} pose!", e.Myo.Arm, e.Myo.Pose);
        }
        #endregion
    }
}

In this example, we create a hub instance. A hub will manage a collection of Myos that come online and go offline and notify listeners that are interested. Behind the scenes, the hub creates a channel instance and passes this into a device listener instance. The channel and device listener combination allows for being notified when devices come online and is the core of the hub implementation. You can manage Myos on your own by completely bypassing the Hub class and creating your own channel and device listener if you’d like. It’s totally up to you.

In the code above, we’ve hooked up several event handlers. There’s an event handler to listen for when Myo devices connect, and a similar one for when the devices disconnect. We’ve also hooked up to an instance of a Myo device for when it changes poses. This will simply give us a console message every time the hardware determines that the user is making a different pose.

When devices go offline, the hub actually keeps the instance of the Myo object around. This means that if you have device A and you hook up to it’s PoseChanged event, if it goes offline and comes back online several times, your event will still be hooked up to the object that represents device A. This makes managing Myos much easier compared to trying to re-hook event handlers every time a device goes on and offline. Of course, you’re free to make your own implementation using our building blocks, so there’s no reason to feel forced into this paradigm.

It’s worth mentioning that the UserInputLoop() method is only used to keep the program alive. The sample code on GitHub actually lets you use some debug commands to read some Myo statuses if you’re interested. Otherwise, you could just imagine this line is replaced by Console.ReadLine() to block waiting for the user to press enter.

Pose Sequences

Without even diving into the accelerometer, orientation, and gyroscope readings, we were looking for some quick wins to building up on the basic API that we created. One little improvement we wanted to make was the concept of pose sequences. The Myo will send events when a pose changes, but if you were interested in grouping some of these together there’s no way to do this out of the box. With a pose sequence, you can declare a series of poses and get an event triggered when the user has finished the sequence.

Here’s an example:


using System;

using MyoSharp.Device;
using MyoSharp.ConsoleSample.Internal;
using MyoSharp.Poses;

namespace MyoSharp.ConsoleSample
{
    /// <summary>
    /// Myo devices can notify you every time the device detects that the user 
    /// is performing a different pose. However, sometimes it's useful to know
    /// when a user has performed a series of poses. A 
    /// <see cref="PoseSequence"/> can monitor a Myo for a series of poses and
    /// notify you when that sequence has completed.
    /// </summary>
    internal class PoseSequenceExample
    {
        #region Methods
        private static void Main(string[] args)
        {
            // create a hub to manage Myos
            using (var hub = Hub.Create())
            {
                // listen for when a Myo connects
                hub.MyoConnected += (sender, e) =>
                {
                    Console.WriteLine("Myo {0} has connected!", e.Myo.Handle);

                    // for every Myo that connects, listen for special sequences
                    var sequence = PoseSequence.Create(
                        e.Myo, 
                        Pose.WaveOut, 
                        Pose.WaveIn);
                    sequence.PoseSequenceCompleted += Sequence_PoseSequenceCompleted;
                };

                ConsoleHelper.UserInputLoop(hub);
            }
        }
        #endregion

        #region Event Handlers
        private static void Sequence_PoseSequenceCompleted(object sender, PoseSequenceEventArgs e)
        {
            Console.WriteLine("{0} arm Myo has performed a pose sequence!", e.Myo.Arm);
            e.Myo.Vibrate(VibrationType.Medium);
        }
        #endregion
    }
}

The same basic setup occurs as the first example. We create a hub that listens for Myos, and when one connects, we hook a new PoseSequence instance to it. If you recall how the hub class works from the first example, this will hook up a new pose sequence each time the Myo connects (which, in this case, isn’t actually ideal). Just for demonstration purposes, we were opting for this shortcut though.

When creating a pose sequence, we only need to provide the Myo and the poses that create the sequence. In this example, a user will need to wave their hand out and then back in for the pose sequence to complete. There’s an event provided that will fire when the sequence has completed. If the user waves out and in several times, the event will fire for each time the sequence is completed. You’ll also notice in our event handler we actually send a vibrate command to the Myo! Most of the Myo interactions are reading values from Myo events, but in this case this is one of the commands we can actually send to it.

Held Poses

The event stream from the Myo device only sends events for poses when the device detects a change. When we were trying to make a test application with our initial API, we were getting frustrated with the fact that there was no way to trigger some action as long as a pose was being held. Some actions like zooming, panning, or adjusting levels for something are best suited to be linked to a pose being held by the user. Otherwise, if you wanted to make an application that would zoom in when the user makes a fist, the user would have to make a fist, relax, make a fist, relax, etc… until they zoomed in or out far enough. This obviously makes for poor usability, so we set out to make this an easy part of our API.

The code below has a similar setup to the previous examples, but introduces the HeldPose class:


using System;

using MyoSharp.Device;
using MyoSharp.ConsoleSample.Internal;
using MyoSharp.Poses;

namespace MyoSharp.ConsoleSample
{
    /// <summary>
    /// Myo devices can notify you every time the device detects that the user 
    /// is performing a different pose. However, sometimes it's useful to know
    /// when a user is still holding a pose and not just that they've 
    /// transitioned from one pose to another. The <see cref="HeldPose"/> class
    /// monitors a Myo and notifies you as long as a particular pose is held.
    /// </summary>
    internal class HeldPoseExample
    {
        #region Methods
        private static void Main(string[] args)
        {
            // create a hub to manage Myos
            using (var hub = Hub.Create())
            {
                // listen for when a Myo connects
                hub.MyoConnected += (sender, e) =>
                {
                    Console.WriteLine("Myo {0} has connected!", e.Myo.Handle);

                    // setup for the pose we want to watch for
                    var pose = HeldPose.Create(e.Myo, Pose.Fist, Pose.FingersSpread);

                    // set the interval for the event to be fired as long as 
                    // the pose is held by the user
                    pose.Interval = TimeSpan.FromSeconds(0.5);

                    pose.Start();
                    pose.Triggered += Pose_Triggered;
                };

                ConsoleHelper.UserInputLoop(hub);
            }
        }
        #endregion

        #region Event Handlers
        private static void Pose_Triggered(object sender, PoseEventArgs e)
        {
            Console.WriteLine("{0} arm Myo is holding pose {1}!", e.Myo.Arm, e.Pose);
        }
        #endregion
    }
}

When we create a HeldPose instance, we can pass in one or more poses that we want to monitor for being held. In the above example, we’re watching for when the user makes a fist or when they have their fingers spread. We can hook up to the Triggered event on the held pose instance, and the event arguments that we get in our event handler will tell us which pose the event is actually being triggered for.

If you take my zoom example that I started describing earlier, we could have a single event handler responsible for both zooming in and zooming out based on a pose being held. If we picked two poses, say fist and fingers spread, to mean zoom in and zoom out respectively, then we could check the pose on the event arguments in the event handler and adjust the zoom accordingly. Of course, you could always make two HeldPose instances (one for each pose) and hook up to the events separately if you’d like. This would end up creating two timer threads behind the scenes–one for each HeldPose instance.

The HeldPose class also has an interval setting. This allows the programmer to adjust the frequency that they want the Triggered event to fire, provided that a pose is being held by the user. For example, if the interval is set to be two seconds, as long as the pose is being held the Triggered event will fire every two seconds.

Roll, Pitch, and Yaw

The data that comes off the Myo can become overwhelming unless you’re well versed in vector math and trigonometry. Something that we’d like to build up and improve upon is the usability of data that comes off the Myo. We don’t want each programmer to have to write similar code to get the values from the Myo into a usable form for their application. Instead, if we can build that into MyoSharp, then everyone will benefit.

Roll, pitch, and yaw are values that we decided to bake into the API directly. So… what exactly are these things? Here’s a diagram to help illustrate:

Roll, Pitch, and Yaw - MyoSharp

Roll, pitch, and yaw describe rotation around one of three axes in 3D space.

The following code example shows hooking up to an event handler to get the roll, pitch, and yaw data:


using System;

using MyoSharp.Device;
using MyoSharp.ConsoleSample.Internal;

namespace MyoSharp.ConsoleSample
{
    /// <summary>
    /// This example will show you how to hook onto the orientation events on
    /// the Myo and pull roll, pitch and yaw values from it.
    /// </summary>
    internal class OrientationExample
    {
        #region Methods
        private static void Main(string[] args)
        {
            // create a hub that will manage Myo devices for us
            using (var hub = Hub.Create())
            {
                // listen for when the Myo connects
                hub.MyoConnected += (sender, e) =>
                {
                    Console.WriteLine("Myo {0} has connected!", e.Myo.Handle);
                    e.Myo.OrientationDataAcquired += Myo_OrientationDataAcquired;
                };

                // listen for when the Myo disconnects
                hub.MyoDisconnected += (sender, e) =>
                {
                    Console.WriteLine("Oh no! It looks like {0} arm Myo has disconnected!", e.Myo.Arm);
                    e.Myo.OrientationDataAcquired -= Myo_OrientationDataAcquired;
                };

                // wait on user input
                ConsoleHelper.UserInputLoop(hub);
            }
        }
        #endregion

        #region Event Handlers
        private static void Myo_OrientationDataAcquired(object sender, OrientationDataEventArgs e)
        {
            Console.Clear();
            Console.WriteLine(@"Roll: {0}", e.Roll);
            Console.WriteLine(@"Pitch: {0}", e.Pitch);
            Console.WriteLine(@"Yaw: {0}", e.Yaw);
        }
        #endregion
    }
}

Of course, if we know of more common use cases that people will be using the orientation data for, then we’d love to bake this kind of stuff right into MyoSharp to make it easier for everyone.

Closing Comments

That’s just a quick look at how you can leverage MyoSharp to make your own C# application to work with a Myo! As I said, MyoSharp is open source so we’d love to see contributions or ideas for suggestions. We’re aiming to provide as much base functionality as we can into our framework but designing it in a way that developers can extend upon each of the individual building blocks.


Hack The North

Hack The North

Hack The North… What The Hack Is That?

Hack The North is Canada’s largest international hackathon. It’s big. It’s bad. It’s awesome. Okay, but what does that even mean?

The idea is that 1000 people get together from all over the world in an event where they’re given 36 hours to create amazing technology hacks. There’s a lack of sleep but no lack of amazing ideas and hacked together proof of concepts that show incredible innovation. Sponsors are present to hand out prizes for best usage of their product or API to competitors as well as mentor them and provide help with problem solving. This year, Hack The North was hosted at The University of Waterloo.

Bro, Do You Even Hack?!

This was my first time ever at a hackathon. I’ve participated in the Ontario Engineering Competition (OEC) which is much smaller scale event with a similar structure–A bunch of students get together and have to come up with a design to solve a problem. I even ran OEC in 2010 with some schoolmates (you might know them at Thalmic Labs) which was a blast. However, this weekend I was sitting on the other side of the table.

I got to hang out with a group of my colleagues at Hack The North at the Magnet Forensics booth. We had a great time representing our company and meeting tons of incredible students from all over the world. We provided assistance where we could with some of the challenges that students were facing, and spoke to them about the important role that our software plays in the life of a forensic examiner/investigator.

What’d You See There?

When I first showed up at Hack The North, it was around 9:00 on Friday night. I got there just in time for the opening ceremonies, which I thought were great. They had live Q&A with a former Facebook employee who has “made it” in the software industry and intros from some of the major sponsors at the event.

Hack The North - Opening Ceremonies

Everyone getting settled for the opening ceremonies at Hack The North.

From that point on, I spent the rest of the time hanging around the Magnet booth… But that doesn’t mean I didn’t see anything awesome. We had people from all over the place coming by to talk to us and pick up some Magnet swag. We handed out an incredible amount of stress balls and couldn’t seem to keep a sufficient supply of them coming. We had our stickers showing up on everything from fuzzy viking hats to laptops to shirts to megaphones. You name it, our stickers made it onto it.

Hack The North - Magnet Viking

Akshay Joshi decorated his hat with Magnet stickers!

Hack The North - Magnet Megaphone

One of the Hack The North organizers was sporting a Magnet sticker on his megaphone.

On the last day of Hack The North, we had participants coming up to our booth to demonstrate some of their awesome hacks. We got to see how Thalmic’s Myo was being incorporated or how other vendors’ APIs were being leveraged to do some really awesome things. We were really impressed with some of the things we saw.

What’s Next?

I think even after the first night of being at Hack The North I was trying to think of what we could do next time or if we even wanted to come back… The answer to the latter was quickly an “absolutely yes!”, so I’m pretty confident we’ll be making an appearance at Hack The North again. There were so many great people at this even that we spoke with that it would be silly not to go back.

I think next year we’d like to participate even more. We learned a lot about the different ways that we could get involved, so things like speaking sessions or workshops would be awesome to get people involved with. We’ll definitely have more stress balls and unique giveaways to please the masses!

Thanks to everyone who made it out to Hack The North. Stay in touch with us! We’d love to hear more from you.

Hack The North - Kelly and Nick

Kelly and I with our #Truth T-shirts and other Magnet gear on at our booth!


Continuous Improvement – One on One Tweaks (Pt. 2)

Continuous Improvement - One on One Tweaks (Pt. 2)

Continuing With Continuous Improvement

I wrote about continuous improvement before and how I’ve been trying to tie that into my leadership role through changes to my one on one process. To recap, at our organization we try to roll continuous improvement into most things that we do. We’re well aware that we’re not going to get things perfect the first time, so as long as we have a process in place to learn, reflect, and adapt, then we can make changes to better our situation. It’s something that’s ongoing and it doesn’t really have an end. So long as your organization is growing and changing over time, or the environment in which your organization is changing over time, having continuous improvement baked into your culture is key to success.

Previously, I mentioned that at Magnet Forensics I hold regular one on ones with my team members. I made a tweak to them that included summarizing notes before holding the one on ones and saw a great improvement. I felt that for now this would be a positive change that I’d like to continue on with. I’ll keep reflecting on whether or not this makes sense over time.

What’s next, then?

Recognition

Recognition is something that I think is fundamental to keeping people engaged, but it looks different for everyone. When I comment on things or share things on social media, I often reflect on how recognition is incredibly important. It’s been a goal of mine to try and do a better job at recognizing my team members for the hard work they’re always putting in.

That was my next hack for continuous improvement. How could I leverage my one on one time to do a better job at recognition? Well, if recognizing my team for things they do is high on my priority list, then it should fall high on the one on one discussion list. The first thing, actually.

So now that I create a summary of topics to go over in our one on ones, I reflect on what my team members say they work on and I toss in other stuff they may not have mentioned. Did they have big accomplishments in our sprint? Did they have things outside of work? Did they have tweaks they suggested for the team to try? Accomplish goals they set for themselves? I try to gather that information and comment on a couple of things at the start of our one on ones now.

I want the team to know that their hard work and their success does not go unnoticed and that they should all keep working to the best of their abilities.

Results?

I’ve only been doing this recently, so I can’t quite say that I’ve noticed big differences. In my opinion, the team has been entering a solid groove over the past few months but it’s hard for me to say whether or not these one on one changes had any impact. I like to think that they did. I’ve heard from several people that they’re really happy with where the team is at.

Has this brought about anything negative? Were there any cons to rolling out this change? I’d say no, not at all. It’s no extra effort for me to reflect on what accomplishments each team member has add. I mean, I’m not writing out lengthy documentation on each accomplishment, but I jot down a couple of points on what I want to call out. I think if anything, that quick exercise has been really positive for myself, if not for the other team member.

So, in the end, I think this small tweak has been a positive change for me in terms of doing a better job of recognizing the team. I also hope that the team has a better understanding that myself and others do see their hard work and efforts.

Keep on it, Team Magnet!


  • Nick Cosentino

    Nick Cosentino

    I work as a team lead of software engineering at Magnet Forensics (http://www.magnetforensics.com). I'm into powerlifting, bodybuilding, and blogging about leadership/development topics over at http://www.devleader.ca.

    Verified Services

    View Full Profile →

  • Copyright © 1996-2010 Dev Leader. All rights reserved.
    Jarrah theme by Templates Next | Powered by WordPress