ngx-serial
Version:
NgxSerial eases the use of the Serial Web API in Angular.
115 lines (110 loc) • 4.07 kB
JavaScript
import { __awaiter } from 'tslib';
class NgxSerial {
constructor(readFunction, options, controlCharacter) {
this.options = { baudRate: 9600, dataBits: 8, parity: 'none', bufferSize: 256, flowControl: 'none' }; //Default
this.controlCharacter = "\n";
this.keepReading = true;
this.readFunction = readFunction;
if (options)
this.options = options;
if (controlCharacter)
this.controlCharacter = controlCharacter;
}
sendData(data) {
return __awaiter(this, void 0, void 0, function* () {
yield this.writer.write(data);
});
}
readLoop() {
return __awaiter(this, void 0, void 0, function* () {
while (this.port.readable && this.keepReading) {
const textDecoder = new TextDecoderStream();
this.readableStreamClosed = this.port.readable.pipeTo(textDecoder.writable);
this.reader = textDecoder.readable
.pipeThrough(new TransformStream(new LineBreakTransformer(this.controlCharacter)))
.getReader();
try {
while (true) {
const { value, done } = yield this.reader.read();
if (done) {
break;
}
if (value) {
this.readFunction(value);
}
}
}
catch (error) {
console.error("Read Loop error. Have the serial device been disconnected ? ");
}
}
});
}
close(callback) {
return __awaiter(this, void 0, void 0, function* () {
this.keepReading = false;
this.reader.cancel();
yield this.readableStreamClosed.catch(() => { });
this.writer.close();
yield this.writableStreamClosed;
yield this.port.close();
callback(null);
});
}
connect(callback) {
return __awaiter(this, void 0, void 0, function* () {
this.keepReading = true;
if ("serial" in navigator) {
// The Web Serial API is supported by the browser.
let nav = navigator;
const ports = yield nav.serial.getPorts();
try {
this.port = yield nav.serial.requestPort();
}
catch (error) {
console.error("Requesting port error: " + error);
return;
}
try {
yield this.port.open(this.options);
}
catch (error) {
console.error("Opening port error: " + error);
return;
}
const textEncoder = new TextEncoderStream();
this.writableStreamClosed = textEncoder.readable.pipeTo(this.port.writable);
this.writer = textEncoder.writable.getWriter();
this.readLoop();
callback(this.port);
}
else {
console.error("This browser does NOT support the Web Serial API");
}
});
}
}
class LineBreakTransformer {
constructor(controlCharacter) {
this.container = "";
this.container = '';
this.controlCharacter = controlCharacter;
}
transform(chunk, controller) {
this.container += chunk;
const lines = this.container.split(this.controlCharacter);
this.container = lines.pop();
lines.forEach((line) => controller.enqueue(line));
}
flush(controller) {
controller.enqueue(this.container);
}
}
/*
* Public API Surface of ngx-serial
*/
/**
* Generated bundle index. Do not edit.
*/
export { NgxSerial };
//# sourceMappingURL=ngx-serial.js.map