Fitbit Flex, dead and won’t charge?

imageMy wife and I both pre-ordered a Fitbit Flex. While it’s not a life-changing device, it’s been generally fun to wear. I’m always interested in the sleep tracking when I travel … “Awake 16x, slept 5 hours.

Last night though, my wife’s Flex had stopped working. The lights wouldn’t show up when the device was tapped and when she used the charger, it wouldn’t begin to charge. I found a few recommendations to use rubber bands to hold the Flex into the charger, cleaning the contacts, and a few more. Cleaning the contacts didn’t help. The charger worked with my Flex, so that meant the rubber band trick wouldn’t help.

I found though on the Fitbit support website this morning though a suggestion that worked! Apparently, you can restart/reset the tracker without loosing data. The steps are easy:

  1. Plug your charging cable into a USB port and insert your Flex as you normally would.
  2. Insert a paperclip into the small pinhole on the back of the charger (I’d never noticed it before, it’s small!)
  3. Press gently on the pinhole for 3-4 seconds. You’ll feel a gentle ‘click’ when you’ve depressed it far enough (although my “one-thousand, two-thousand, three-thousand” count actually got to 6). The lights flashed a few times, and it started charging a few seconds later.

I’m posting this here as my searching the night before hadn’t turned up that specific support web site page. It may be because the web page is poorly titled and applies to four of their trackers.

Hope this helps someone else.

Sending a socket to a forked process in Node.JS

If you want to fork a process in Node and pass a socket, the current Node documentation has a rather odd example, so I’ve simplified it here for my own sanity (further complicated by the fact that the WebStorm debugger can’t debug a forked Node.JS process, which confused me for too long). Hopefully someone else finds this useful at some point.

Step 1, in a file called app.js:

var child = require('child_process').fork('socket_handler.js');

// Open up the server and send sockets to child
var server = require('net').createServer();

server.on('connection', function (socket) {
    child.send('socket', socket);
    server.getConnections(function(err, count) {
        console.log("Connections: " + count);
    });
});
server.listen(1337);

And then, in a file called socket_handler.js which is located in the same directory as app.js:
process.on('message', function(message, socket) {
    socket.on('data', function(data) {
        // really poor echo ... :)
        socket.write(data);
    });
});

In this case, the fork happens upon application startup by calling the fork method of the child_process module. It starts by executing the code in socket_handler.js. As this is a new instance of the V8 engine used by Node.JS, remember there’s a sizable overhead to a forked process.

After creating the server and listening on port 1337, when a connection is made (which can be tested by a terminal emulator or telnet), the socket is passed to the forked process. In fact, it’s not really the object as much as it’s the handle to the new socket.

The send method takes two parameters, a string message which can be any identifier you want, and the the handle, or socket in this case.

The forked process receives the message via the message event on the process. If you’re sending more than one message, you can add conditional logic to handle the type of message in the event handler. As part of the call to fork, you can also pass command line arguments and read them using process.argv.

Mongoose plugin runs for every new Schema

If you want to consistently apply changes to every Schema in Mongoose, it’s simple. Below is an example.

var mongoose = require('mongoose');

var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}");
mongoose.plugin(function(schema, opts) { 
    schema.statics.isObjectId = function(id) { 
        if(id) { 
            return checkForHexRegExp.test(id); 
        } 
        return false; 
    }; 
}); 
var AnimalSchema = mongoose.Schema({ name: String }); 
var Animal = mongoose.model("Animal", AnimalSchema); if(Animal.isObjectId("521b4891039857e07aae695a")) { 
    var animal = new Animal(); // something more interesting here ... 
}

The code above uses the plugin function on the global mongoose object to add a new plugin. When you add a plugin using that technique, it runs for every schema that is constructed.

So, in this case, I’ve added a static function to every Schema called isObjectId which uses a simple regular expression (liberally borrowed straight from the bson ObjectId source code) to test whether a string looks like a valid ObjectId (in fact, a 24 character HEX string).

Now, as new models are created (mongoose.model), the Schema is first passed to any defined plugins. The plugin adds the new function isObjectId. As you can see, the new Model has a static method called isObjectId.

The plugin will not affect any Schemas/Models that were defined before the plugin was added.

Using this technique, you could add standardized fields, indexes, etc. without repeating the same code to all Schemas. Of course, you can also use the plugin method defined on a Schema to selectively add functionality.

var isObjectIdPlugin = function(schema, opts) {
    schema.statics.isObjectId = function(id) {
        if(id) {
            return checkForHexRegExp.test(id);
        }
        return false;
    };
};


var AnimalSchema = mongoose.Schema({
    name: String
});

AnimalSchema.plugin(isObjectIdPlugin);

var Animal = mongoose.model("Animal", AnimalSchema);

if(Animal.isObjectId("521b4891039857e07aae695a")) {
    var animal = new Animal();
    // something more interesting here ...
}

Above, the code applies the plugin to only the AnimalSchema using the plugin method.

Of course, adding the same method statically may not be very useful – instead it probably belongs somewhere in a utility class (and really it’s too bad it’s not just exposed directly by the BSON ObjectId class).

Using Sqlite and C# to determine if a specified table exists

I had need of a bit of code in C# to determine whether several tables in a Sqlite database had been created, so …

public static class DbExtensions
{
    /// <summary>
    /// Determines whether the table exists
    /// </summary>
    /// <param name="connection">Existing, opened, database connection</param>
    /// <param name="tableName">The name of the table to test for.</param>
    /// <returns>True if table exists.</returns>
    public static bool TableExists(this IDbConnection connection, string tableName)
    {
        Debug.Assert(connection != null);
        Debug.Assert(!string.IsNullOrWhiteSpace(tableName));

        var cmd = connection.CreateCommand();
        cmd.CommandText = @"SELECT COUNT(*) FROM sqlite_master WHERE name=@TableName";
        var p1 = cmd.CreateParameter();
        p1.DbType = DbType.String;
        p1.ParameterName = "TableName";
        p1.Value = tableName;
        cmd.Parameters.Add(p1);

        var result = cmd.ExecuteScalar();
        return ((long)result) == 1;
    }
}

Nothing too complex … only determining that the list of tables is stored in a system table named sqlite_master. If you want to find all indexes that have dependencies on a specific table, you can instead use the column tbl_name.

If you’re using Dapper and the DapperExtensions, you might find this useful:

_connection = new System.Data.SQLite.SQLiteConnection();
DapperExtensions.DapperExtensions.SqlDialect = new DapperExtensions.Sql.SqliteDialect();
_connection.ConnectionString = new DbConnectionStringBuilder()
{
    {"Data Source", "thumbnailer.db"},
    {"Version", "3"},
    {"FailIfMissing", "False"},
}.ConnectionString;

First, it creates the SQLite connection (nuget) and then configures the DapperExtensions to use the SqliteDialect. What that means is that the extensions will generate SQL that actually works! :) Finally, in my case, I wanted the DB to be created if it didn’t exist, so I set FailIfMissing to False.