Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code.org Integration #3

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 23 additions & 6 deletions client/MBFirmataClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,21 @@ SOFTWARE.
* Clients can listen for DAL events, digital pin changes, or analog channel updates.
*/

const serialport = require('serialport');
const {TextEncoder, TextDecoder} = require('util');
let serialport;
let TextEncoder, TextDecoder;

// If running outside of the browser, create the TextEncoder/TextDecoder
if (typeof window === 'undefined' || !window.TextEncoder) {
TextEncoder = require('util').TextEncoder;
TextDecoder = require('util').TextDecoder;
} else {
TextEncoder = window.TextEncoder;
TextDecoder = window.TextDecoder;
}

class MicrobitFirmataClient {
constructor() {
constructor(port) {
serialport = port ? port : require('serialport');
this.addConstants();
this.myPort = null;
this.inbuf = new Uint8Array(1000);
Expand Down Expand Up @@ -109,10 +119,13 @@ class MicrobitFirmataClient {

// Connecting/Disconnecting

/**
* @returns {Promise} when port has been opened or if no port found
*/
connect() {
// Search serial port list for a connected micro:bit and, if found, open that port.

serialport.list()
return serialport.list()
.then((ports) => {
for (var i = 0; i < ports.length; i++) {
var p = ports[i];
Expand All @@ -127,13 +140,17 @@ class MicrobitFirmataClient {
// Attempt to open the serial port on the given port name.
// If this fails it will fail with an UnhandledPromiseRejectionWarning.
console.log("Opening", portName);
this.setSerialPort(new serialport(portName, { baudRate: 57600 }));
return this.setSerialPort(new serialport(portName, { baudRate: 57600 }));
} else {
console.log("No micro:bit found; is your board plugged in?");
return null;
}
});
}

/**
* @returns {Promise} when board version is set
*/
setSerialPort(port) {
// Use the given port. Assume the port has been opened by the caller.

Expand All @@ -151,7 +168,7 @@ class MicrobitFirmataClient {

// get the board serial number (used to determine board version)
this.boardVersion = '';
serialport.list()
return serialport.list()
.then((ports) => {
for (var i = 0; i < ports.length; i++) {
var p = ports[i];
Expand Down