Javascript Checksum Builder

Discussion in 'General Discussion' started by ievolve, Dec 24, 2011.

  1. ievolve

    ievolve

    Joined:
    Mar 20, 2010
    Messages:
    112
    Likes Received:
    1
    Location:
    Idaho
    I am in the process of building out an http proxy to C-Bus using my CNI and nodejs (nodejs.org). This will enable to enable me to hit a webpage and control my c-bus stuff, plus give me a platform to weave in my other stuff like sonos and whatnot. Contemplating putting it up on github.

    In the process I banged my head against the wall for a while on getting the checksums right for the commands. I figured this code may help someone else who comes along looking for a way to build the command strings they need to write to the CNI socket.

    (note, "device" is the hex value of your device, like "0D", "command" is either "on" or "off", I'll support more commands later)

    Code:
    function cmdString(device,command) {
        var turnon = '05380079';
        var turnoff = '05380001';
        
        if(command=='on') {
            message = turnon + device;
        }
        else {
            message = turnoff + device;
        }
    
        var sum=0;
        var len=message.length;
        
        for(var i=0;i<len;i=i+2) {
            bt=message.substring(i,i+2);
            ibt=parseInt(bt,16);
            sum=sum+ibt;
        }
        
        var m=(sum % 256);
        var check=(256+((~m)+1)).toString(16).toUpperCase();
    
        while (check.length < 2) {
            check = "0" + check;
        }
        
        return '\\' + message + check + 'g' + '\r';
    }
     
    Last edited by a moderator: Dec 26, 2011
    ievolve, Dec 24, 2011
    #1
Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.