Skip to content

Instantly share code, notes, and snippets.

@usefulthink
Created June 26, 2017 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save usefulthink/1e08ebf504a68bf04008646dedf81d12 to your computer and use it in GitHub Desktop.
Save usefulthink/1e08ebf504a68bf04008646dedf81d12 to your computer and use it in GitHub Desktop.
A fivetwelve-driver for the enttec usbopen-interface.
/**
* A fivetwelve-driver for the enttec usbopen-interface.
*
* @example
* import fivetwelve from 'fivetwelve';
* import Serialport from 'serialport';
* import EnttecUsbOpenDriver from 'fivetwelve-driver-enttec-usbopen';
*
* // I read somewhere that connection settings like baudrate etc are not
* // required as it's just a virtual serialport or something like that
* const usbproSerialport = new Serialport('/dev/something');
*
* // configure output
* const output = fivetwelve(
* new EnttecUsbOpenDriver(usbproSerialport));
*/
export default class EnttecUsbOpenDriver {
/**
* Initializes the driver for the given serialport.
* @param {Serialport} serialport A ready configured node-serialport instance.
* Setting up the serialport-connection has to be done externally.
*/
constructor(serialport) {
/**
* @type {Serialport}
*/
this.serialport = serialport;
this.opened = this.awaitSerialportOpened();
}
/**
* Sends the given values to the dmx-interface over the serialport.
* @param {Buffer} buffer A buffer with the dmx-values to be sent.
* @returns {Promise} A promise that will be resolved when the buffer is
* completely sent.
*/
send(buffer) {
// dmx-transmission is 0x00 as start-signal and 512 bytes payload
const frameBuffer = new Buffer(513);
frameBuffer.writeUInt8(0, 0);
buffer.copy(frameBuffer, 1);
return this.write(frameBuffer);
}
/**
* Returns a Promise that is resolved once the serialport is opened.
* @returns {Promise.<Serialport>} A promise resolving with the
* node-serialport instance.
* @private
*/
awaitSerialportOpened() {
if (this.serialport.isOpen()) {
return Promise.resolve(this.serialport);
}
return new Promise((resolve, reject) => {
this.serialport.on('open', error => {
if (error) {
return reject(error);
}
return resolve(this.serialport);
});
});
}
/**
* Writes the raw data to the serialport.
* @param {Buffer} buffer A buffer to be sent to the serialport.
* @returns {Promise} a promise that is resolved when the buffer was
* completely sent.
* @private
*/
write(buffer) {
return this.opened.then(serialport => {
return new Promise((resolve, reject) => {
serialport.write(buffer, err => {
if (err) {
return reject(err);
}
serialport.drain(() => resolve());
});
});
});
}
}
/**
* @typedef {object} Serialport
* @property {function} write
* @property {function} drain
* @property {function} isOpen
* @property {function} on
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment