node-serialport-bindings-cpp/lib/bindings/linux.js
Francis Gulotta 6455ecbb51 [unix] New read/write subsystem (#1212)
This has always been the dream. Use `fs.read` and `fs.write` to do reading and writing. To make that happen I've created a cross platform `Poller` object that notifies us once on `readable` and `writable` states.

- Reduce large write cpu usage from 100% to 1-2%
- Replace ReadPoller with a multi purpose poller because you can only have a single uv_poll_t on a fd at a time because reasons
- Experimented with doing this all in c++, maybe there are gains to doing that but I'd never finish.
- Some unrelated eslint changes
- Arduino echo should just echo, writing random bytes was messing it up
- use a file to disable tests in envs
- read and write errors can trigger disconnects
- disconnect event only happens if there are listeners, otherwise error events will be triggered
- a disconnect during write will always have a write error too
- win32 bindings seem to only trigger disconnects on writes
2017-07-05 09:12:31 -04:00

90 lines
2 KiB
JavaScript

'use strict';
const binding = require('bindings')('serialport.node');
const BaseBinding = require('./base');
const linuxList = require('./linux-list');
const Poller = require('./poller');
const promisify = require('../util').promisify;
const unixRead = require('./unix-read');
const unixWrite = require('./unix-write');
const defaultBindingOptions = Object.freeze({
vmin: 1,
vtime: 0
});
class LinuxBinding extends BaseBinding {
static list() {
return linuxList();
}
constructor(opt) {
super(opt);
this.bindingOptions = Object.assign({}, defaultBindingOptions, opt.bindingOptions || {});
this.fd = null;
}
get isOpen() {
return this.fd !== null;
}
open(path, options) {
return super.open(path, options)
.then(() => {
this.openOptions = Object.assign({}, this.bindingOptions, options);
return promisify(binding.open)(path, this.openOptions);
})
.then((fd) => {
this.fd = fd;
this.poller = new Poller(fd);
});
}
close() {
return super.close()
.then(() => {
const fd = this.fd;
this.poller.stop();
this.poller = null;
this.openOptions = null;
this.fd = null;
return promisify(binding.close)(fd);
});
}
read(buffer, offset, length) {
return super.read(buffer, offset, length)
.then(() => unixRead.call(this, buffer, offset, length));
}
write(buffer) {
return super.write(buffer)
.then(() => unixWrite.call(this, buffer));
}
update(options) {
return super.update(options)
.then(() => promisify(binding.update)(this.fd, options));
}
set(options) {
return super.set(options)
.then(() => promisify(binding.set)(this.fd, options));
}
get() {
return super.get()
.then(() => promisify(binding.get)(this.fd));
}
drain() {
return super.drain()
.then(() => promisify(binding.drain)(this.fd));
}
flush() {
return super.flush()
.then(() => promisify(binding.flush)(this.fd));
}
}
module.exports = LinuxBinding;