Monthly Archives: January 2010

You are browsing the site archives by month.

Hacking Polar Watch WebSync Software

I recently purchased a Polar FT-40 watch to monitor my fitness level and track my workouts better. I like the watch so far although I’m not ready to give a thorough review on it just yet. Today, I received the Polar FlowLink data transfer unit that allows me to transfer the data on my watch to Polar’s website. It allows you to chart your progress and do all sorts of interesting things with the data. I was surprised how easy and smoothly the software worked. However, I wanted the data on my desktop so I could do more with it. I wanted to provide my own charts and data views in Excel. I wanted to be able to post it to my blog easily or write a WordPress widget to display my data. That said, I decided to look at what the WebSync software was written in. I had a sneaking suspicion that it might be .NET — I was right!

So, I decided to look under the hood and see if I could tackle writing my own front end to their devices. What I found should horrify anyone who has ever read past Chapter 1 of a reasonable “C#” book.

I started by pulling in the obvious assemblies to see what was built. The project looked reasonably well built. There was enough evidence ot see that there was at least SOME design put into the application. I even found some tests in tone assembly — at least there were some tests (checked that off on their requirements eh?). When I took a look at the EXE, however, what I saw shocked me. So I started drilling down into WebSync.exe. I found a Polar.WebSync.Program class with a static Main() method. Bingo – my entry point. I immediately saw some minor concerns. For instance, they were using a Mutex to provide the functionality of a Singleton pattern. Worse yet, they were calling GC.KeepAlive() on the Mutex. Interesting. They did, however, have what looked like an external exception reporting framework, so that at least gave me SOME hope.

I found Application.Run that was starting a new WebSyncTrayForm() so I naturally followed to the form constructor. In a big Try/Catch block (with no code executing in the “catch” portion), I found a TextBox-style TraceListener was added to the form — mmkay. That’s a decent idea I suppose, but let’s look at the form’s Load event. Oh my! I closed my eyes and looked again. I closed then and then looked one more time. Oh, these folks must have written some VB code with “DoEvents” called more than a few times in their past history. Tell me what you see wrong with this:

WARNING: Not good example code!!

private void WebSyncTrayForm_Load(object sender, EventArgs e)
{
    base.Visible = false;
    this.notifyIcon.Tag = this.notifyIcon.Icon;
    this.toolTip = this.notifyIcon.Text;
    this.notifyIcon.Text = this.toolTip + "n" +
        Resources.StatusInitializing;
    this.timerDaemon = new Timer();
    this.timerDaemon.Interval = 0x2710;
    this.timerDaemon.Tick += new EventHandler(this.timerDaemon_Tick);
    this.timerDaemon.Start();
    this.timerDaemon_Tick(this.timerDaemon, EventArgs.Empty);
}

Seriously? These guys set up a timer, and then start it, and then MANUALLY call the Tick function they just set up! (how do they know it hasn’t been executed already between the start call and a thread interuption that might have caused the Tick event to get executed next.

Then I looked at the tick event and I couldn’t believe what I was seeing.

WARNING: Not good example code!!

private void timerDaemon_Tick(object sender, EventArgs e)
{
    this.retryCount++;
    try
    {
        if (this.retryCount == 6)
        {
            this.timerDaemon.Interval = 0xea60;
        }
        this.mounter = new WristUnitListener();
        this.mounter.WristUnitMounted +=
                new WristUnitConnectionEventHandler(this.WristUnitMounted);
        this.mounter.WristUnitUnmounted +=
                new WristUnitConnectionEventHandler(this.WristUnitUnmounted);
        this.mounter.Start();
        this.DoInitialConfig(null);
        this.timerDaemon.Stop();
        this.timerDaemon.Dispose();
        this.timerDaemon = null;
        this.notifyIcon.Icon = this.notifyIcon.Tag as Icon;
        this.notifyIcon.Text = this.toolTip + "n"
                + Resources.StatusRunning;
        Trace.WriteLine("Connected to Polar Daemon.", "WebSync");
    }
    catch (ConnectionException exception)
    {
        if (this.retryCount < 6)
        {
            Trace.WriteLine(
               string.Format("Couldn't connect to Polar Daemon ({0})",
                              exception.CodeString),
                             "WebSync");
        }
        if (this.retryCount == 6)
        {
            Trace.WriteLine(
               string.Format("Couldn't connect to Polar Daemon ({0})",
                             exception.CodeString),
                             "WebSync");
            Trace.WriteLine(
               string.Format("WebSync couldn't initialize properly." +
                             "Please check that Polar Daemon service is running.",
                              new object[0]), "WebSync");
            this.notifyIcon.Icon = Resources.IconExclamation;
            this.notifyIcon.Text = this.toolTip + "n" + Resources.StatusInitError;
            this.notifyIcon.ShowBalloonTip(0x2710, Resources.ToolTipProblemTitle,
                              Resources.ToolTipInitError, ToolTipIcon.Warning);
            this.notifyIcon.BalloonTipClicked +=
                new EventHandler(this.notifyIcon_BalloonTipClicked);
        }
    }
}

OK. These guys are on crack! They have a retry counter that apparently will never be more than 1. Because the tick event will go away and there is no loop in this code, the retryCount will always be 1 (taking note that they decided to start with a 1-based counting system rather than zero because n-1 is a bit complex). That at didn’t stop them from checking to see if it was equal to 6, and if so, changing the interval.

In the tick event, they create a new instance of a WristUnitListener and hook up events to it EACH time. They call start on the WristUnitListener instance and then STOP the timer and dispose of it! Never mind the fact that this timer execution is owned by the main thread rather than the timer tick function — when a timer stops itself, disposes of itself, and then nulls itself, it’s time to reevaluate your understanding of background-thread polling. This is insane! I have no idea how this even works. I can only hope that, as I dig in further WristUnitListener actually works the way it is supposed to and the only thing that sucks is the WebForms code.

Update January 13th, 2010 1:15AM PST:

I was able to successfully hack around with the API and get data off the watch with little effort. The trick was to working around some wonky and non-working APIs. To their defense 1) this API and software has to work with multiple watches 2) wasn’t intended to be consumed by other devs 3) was written with interop for the native libraries accessing the hardware, 4) does show signs of some intelligent thinking (although does need considerable amounts of re-work). As you can see by the image, I can even pull the bitmap logo off of the watch and, if I so desire, set it.

This is far from complete but I will work it over some this week and this weekend before publishing the source on Codeplex. Let me know if there is something in particular that you’d like to see.

 

Update July 7th, 2010 12:01AM PST:

I have posted this code to codeplex as-is. You can find it here: http://polarsync.codeplex.com/

If you would like to contribute source code or improve the project for others in the community, please send me a request and I’ll approve you. I don’t intend to maintain the code or improve it.

Poll: Where would you categorize SQL Azure?

I own the sites for all of the data stack on MSDN. I’m trying to categorize the SQL Azure technology where it makes the most sense to put it. I can obviously categorize this under SQL Server (as it currently sits), or I can move it to the Azure development center. Obviously I can link to it from either place, but I’m trying to decide where it belongs in the overall scheme of things. Your thoughts are appreciated. Vote, comment, do whatever you want, but please speak up and retweet this (link above) so others can too!

[poll id=”3″]

Thanks for your assistance!

Life hack: Getting better gas mileage

On my way to a metric-based lifestyle, I started taking a closer look at my gas mileage. This was a metric that I have been collecting for a while and thought I should be able to improve rather easily – lending itself to improved daily discretionary spending.

I recently purchased a 2010 Ford Fusion Sport. According to Ford’s specs I should be getting 18mpg in the city and 27mpg on the highway. I’ve put 11,000 miles on my car in 6 months – most of them highway driving so I should be getting near that top MPG range in this car. However, I rarely broke 300 miles on a single 17.5 gallon fuel tank (I usually filled up with 14-15 gallons). In fact, most of my fuel-ups netted me 270 miles. For the longest time, I couldn’t get above 18.x miles per gallon according to the sensor on my car. This left lots of room for improvement in a car that says it can do a lot better.

I keep a journal of my gas fuel-ups. Here are the metrics before my changes:

Avg Miles/Tank Avg Gallons/Fuel-up Avg Miles/Gallon Est. Gallons/Year* Est. Fuel Cost/Year**
272 14.53 18.71989 1282.059 $3,653.87

* Based on 24,000 miles a year (my current pace)
** Based on $2.85/gallon average price tag

I just had to do better. I used to get a thrill out of getting 300 miles out of a tank of gas. I wanted to know what it was like to get 350 miles — maybe more. Without any research on the web, I just tried a few things – things that might be common sense for others, but were just not a big deal for me. Here is what I decided to do.

No More Distracted Driving

I have a ton of gadgets that can vie for my attention while I’m driving. In the past, those gadgets would get my attention – particularly if I was in stop and go traffic. I decided to make a habit of ignoring everything but driving. After driving through three tanks of gas, I noticed that I was consistently getting around 300 miles per tank. Distracted driving seems to have cost me about 10% of my fuel efficiency!

No More Aggressive Driving

I’ve lived in a lot of big cities where it was eat-or-be-eaten when it comes to driving. Again, in stop and go traffic, I would tend to stay very close to the bumper of the next car so others wouldn’t cut me off. I made a conscious decision once again to start driving far less aggressively. I use my cruise control when I can. I stay far behind the cars in front of me. A defensive driving instructor would be proud! Oddly enough, I feel a lot less stressed when I just acknowledge that people are going to keep cutting me off and that’s ok. The result? My last two fill-ups gave me over 350 miles per tank and my current tank is on target to give me about 365 if it keeps on pace! This is amazing.

Results

I’ve nearly squeezed an extra 100 miles out of every tank just by changing driving behavior! Let’s put this in perspective. Here are the metrics after my changes (assuming I get the 365 miles out of this tank):

Avg Miles/Tank Avg Gallons/Fuel-up Avg Miles/Gallon Est. Gallons/Year* Est. Fuel Cost/Year**
357.5 14.53 24.60427 975.4406 $2,780.01

If you compare that against my previous cost, I’m on track to save $873.86 this year – and that’s if I don’t change anything else. Being that this is an iterative process, I’m going to try more behavior tweaking to try and get my MPG up.

Life Hack: A metrics-based lifestyle this decade

I’ve never considered myself to be a “life hacker” by any means. I have been concentrated on my career and comfort in the past decade and that came at some great costs. So, I decided to start formulating a plan to make changes to my life based on metrics. I will become a life hacker — for better or worse.

Metrics imply measurability and that’s what I intend to concentrate on at first — things that I can measure, change behavior, then measure again. While there is non-empirical consequence to many decisions that I make on a daily basis, I decided to start here. For instance, my first metric-based decision of the decade was to avoid stopping at Starbucks this morning. I estimate that a stop at Starbucks averages 15 minutes of my time, $5 of my wealth, and a negative drag on my health (250 calories, 47 carbs, and 180mg of sodium taken from my daily allowances of those items).  A case could be made that this has decreased my momentary happiness. I’m not measuring that. In fact, I’m trying to do away with decisions based on immediacy. While my short-term aggrivation is great, I am speculating that over time this will turn into a net-positive for my happiness.

There are a lot of things that I want to change in my life this decade. But I’m going to concentrate on a few major areas, and break them down further as it makes sense to do so. Hopefully at some point I’ll be able to come up with an automated process to view my progress and give myself “triggers” to remind me when I’m slipping. Eventually, I’d like every decision I make to tigger a flurry of facts in my head before moving forward. That should also make its way into my structured planning for the day, week, month, quarter and year.

So here are the areas where I’m going to concentrate:

  • Health – I’d like to improve my health through better nutrician, exercise, and sleeping habits. I will be measuring:
    • Daily intake of calories, carbohydrates, protein, fat, fiber, sodium, and water.
    • Daily exercise in the form of pedometer-tracked steps, cardio minutes, weight lifted and reps per exercise, and stretching minutes.
    • Weekly weight
    • Hour slept and number of times I woke up
  • Wealth – I need to start planning and budgeting better. While I’m not exactly a spend-aholic, I can do better in my planning and spending decisions. I will track:
    • Monthly savings contribution as a $ amount and a percentage of income
    • Weekly investment changes
    • Daily discretionary spending
    • Quarterly credit score
  • Time – This is where I hurt the most. I don’t have enough time in the day to do everything I want. I’m hoping making metric-based decisions will free up some time and help me better plan. I will track:
    • Time spent blogging
    • Time spent learning
    • Time spent on household chores
    • Time spent commuting
  • Others – I will add additional metrics as I think of them or as I see a need to improve this process.

Obviously each of these are going to need base-lined for a month or so. I will be using whatever tools I can to accomplish this base-line. I’m planning on using an Omron HJ-720ITC Pocket Pedometer with Health Management Software to track my steps. I’m using the iPhone LiveStrong app as well as CalorieKing to track my daily nutrition and exercise metrics. I’m considering the Zeo Sleep Coach after Scott Hanselman recommended it, but for now I’ll just use some plain old pen/paper tracking, so to speak. I may also pick up on the Nike+iPhone app at some point, but not just yet.

If you are interested in tracking my progress and keeping me honest, I will be posting what I can under the “life hack” category on this site.

Happy new year everyone!