Last active
April 19, 2019 00:48
-
-
Save CrashedBboy/3878910b216e1689eea6e15d0523cfef to your computer and use it in GitHub Desktop.
Sample of serial device API for Chrome applications.
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
// class | |
function Serial(path, birate, dataBit, stopBit, parityBit, stageManager) { | |
this.path = path; | |
this.birate = birate; | |
this.dataBit = dataBit; | |
this.stopBit = stopBit; | |
this.parityBit = parityBit; | |
this.stageManager = stageManager; | |
this.connectionId = null; | |
this.buffer = ""; | |
} | |
// create a connection | |
Serial.prototype.connect = function() { | |
chrome.serial.connect( | |
this.path, | |
{ | |
persistent: false, | |
bitrate: this.birate, | |
dataBits: this.dataBit, | |
parityBit: this.parityBit, | |
stopBits: this.stopBit | |
}, | |
(function(info) { | |
this.connectionId = info.connectionId; | |
chrome.serial.onReceive.addListener(this.onReceive.bind(this)); | |
}).bind(this) | |
); | |
} | |
// disconnect all connections | |
Serial.prototype.reset = function() { | |
chrome.serial.getConnections((function(cons){ | |
cons.forEach(function(item, index, array) { | |
chrome.serial.disconnect(item.connectionId, function(result) { | |
console.log(result); | |
}); | |
}); | |
}).bind(this)); | |
} | |
// receiver function | |
Serial.prototype.onReceive = function(info) { | |
if (info.data) { | |
var c = ab2str(info.data); | |
if (c === '\n' || c === '\r\n') { | |
if (this.buffer != "") { | |
this.stageManager.updateWeight(parseFloat(this.buffer.split(",")[2])); | |
this.buffer = ""; | |
} | |
} else if (c != '\n') { | |
this.buffer += c; | |
} | |
} | |
} | |
function ab2str(buf) { | |
return String.fromCharCode.apply(null, new Uint8Array(buf)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment