Skip to content

Commit

Permalink
Merge pull request #3 from epeach/code-dot-org-integration
Browse files Browse the repository at this point in the history
Allow serialport to be overridden, allow the TextEncoder, TextDecoder to work in node and browser, and connecting to a port now returns a promise for async/progress reporting.
  • Loading branch information
JohnVidler authored Feb 20, 2023
2 parents b46496d + 119d2e1 commit 91e0610
Showing 1 changed file with 23 additions and 6 deletions.
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 @@ -132,10 +142,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 @@ -150,13 +163,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 @@ -174,7 +191,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

0 comments on commit 91e0610

Please sign in to comment.