Created
March 12, 2016 22:35
-
-
Save eni23/d4b6aea162c991b37049 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var cdc_device = function(){ | |
this.ready = false; | |
this.error = false; | |
// init device | |
this.init = function( callback ){ | |
digicdc.register( | |
(function success(){ | |
console.log("device is ready"); | |
this.ready = true; | |
if (callback) callback(msg); | |
}).bind(this), | |
(function error(){ | |
this.error = true; | |
}).bind(this) | |
); | |
}; | |
// read and call callback | |
var cb_read = function(cb) { | |
digicdc.read( | |
// success | |
function(t){ | |
cb(t); | |
}, | |
// error | |
function(e) { | |
cb(""); | |
} | |
); | |
}; | |
// write and call callback | |
var cb_write = function(data, cb){ | |
digicdc.write( | |
data, | |
function(){ | |
cb(); | |
}, | |
function(){ | |
cb(); | |
} | |
); | |
}; | |
// public available read | |
this.read = function(callback){ | |
cb_read( | |
function(){ | |
if (callback) callback(); | |
} | |
); | |
}; | |
// public available write | |
this.write = function(data, callback){ | |
cb_write( | |
data, | |
function(){ | |
if (callback) callback(); | |
} | |
); | |
}; | |
// read device multiple times | |
var read_multiple = function( callback_end, delay, repetitions ){ | |
var res = ""; | |
var curr_read = 0; | |
read_multiple_cb( callback_end, delay, repetitions, curr_read, res ); | |
}; | |
// callback for multiread | |
var read_multiple_cb = function(callback_end, delay, repetitions, curr_read, res){ | |
if (repetitions == curr_read){ | |
callback_end(res); | |
return; | |
} | |
else { | |
cb_read( | |
function(r){ | |
//console.log("read step, count="+curr_read+" data="+r); | |
res = res + r; | |
curr_read++; | |
setTimeout( | |
function(){ | |
read_multiple_cb( callback_end, delay, repetitions, curr_read, res ); | |
}, | |
delay | |
); | |
} | |
); | |
} | |
}; | |
// write cmd to device and read output | |
this.cmd = function(cmd, callback, read_repetitions, read_delay){ | |
if (read_repetitions) var num_reads = read_repetitions; | |
else var num_reads = 4; | |
if (read_delay) var delay = read_delay; | |
else var delay = 5; | |
cb_write( | |
cmd, | |
function(){ | |
read_multiple( | |
function(data){ | |
if (callback){ | |
var u8arr = new Uint8Array(data.length); | |
for (i in data){ | |
u8arr[i] = data.charCodeAt(i); | |
} | |
callback(u8arr); | |
} | |
}, | |
delay, | |
num_reads | |
); | |
} | |
); | |
}; | |
return this; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment