From 975b270ba3b8cc2f3299cd741359c4b2dcd548f8 Mon Sep 17 00:00:00 2001 From: Munyiri Kamau Date: Wed, 16 Nov 2016 19:30:47 -0800 Subject: [PATCH 1/3] Adding WindowsBinding reading --- lib/bindings-win32.js | 28 ++++++++- src/serialport.cpp | 51 +++++++++++++++++ src/serialport.h | 15 +++++ src/serialport_win.cpp | 126 ++++++++++++++++++++++++++++++++++------- 4 files changed, 199 insertions(+), 21 deletions(-) diff --git a/lib/bindings-win32.js b/lib/bindings-win32.js index 318bae0..8f809cc 100644 --- a/lib/bindings-win32.js +++ b/lib/bindings-win32.js @@ -19,7 +19,33 @@ function WindowsBinding(opt) { this.fd = null; }; -WindowsBinding.prototype.read = require('./read-unix'); +WindowsBinding.prototype.read = function (buffer, offset, length, cb) { + if (!Buffer.isBuffer(buffer)) { + throw new TypeError('"buffer" is not a Buffer'); + } + + if (typeof offset !== 'number') { + throw new TypeError('"offset" is not an integer'); + } + + if (typeof length !== 'number') { + throw new TypeError('"length" is not an integer'); + } + + if (buffer.length < offset + length) { + throw new TypeError('buffer is too small'); + } + + if (typeof cb !== 'function') { + throw new TypeError('"cb" is not a function'); + } + + if (!this.isOpen) { + return asyncError(cb, new Error('Port is not open')); + } + + binding.read(this.fd, buffer, offset, length, cb); +}; WindowsBinding.prototype.open = function(path, options, cb) { if (!path) { diff --git a/src/serialport.cpp b/src/serialport.cpp index c7963c6..3b25d4d 100644 --- a/src/serialport.cpp +++ b/src/serialport.cpp @@ -336,6 +336,56 @@ void EIO_AfterWrite(uv_work_t* req) { delete queuedWrite; } +NAN_METHOD(Read) { + // file descriptor + if (!info[0]->IsInt32()) { + Nan::ThrowTypeError("First argument must be an int"); + return; + } + int fd = Nan::To(info[0]).ToLocalChecked()->Value(); + + // buffer + if (!info[1]->IsObject() || !node::Buffer::HasInstance(info[1])) { + Nan::ThrowTypeError("Second argument must be a buffer"); + return; + } + v8::Local buffer = info[1]->ToObject(); + char* bufferData = node::Buffer::Data(buffer); + size_t bufferLength = node::Buffer::Length(buffer); + + // offset + if (!info[2]->IsInt32()) { + Nan::ThrowTypeError("Third argument must be an int"); + return; + } + int offset = Nan::To(info[2]).ToLocalChecked()->Value(); + + // bytes to read + if (!info[3]->IsInt32()) { + Nan::ThrowTypeError("Fourth argument must be an int"); + return; + } + int bytesToRead = Nan::To(info[3]).ToLocalChecked()->Value(); + + // callback + if (!info[4]->IsFunction()) { + Nan::ThrowTypeError("Fifth argument must be a function"); + return; + } + + ReadBaton* data = new ReadBaton(); + memset(data, 0, sizeof(ReadBaton)); + data->fd = fd; + data->offset = offset; + data->bytesToRead = bytesToRead; + data->bufferLength = bufferLength; + data->callback.Reset(info[4].As()); + + uv_work_t* req = new uv_work_t(); + req->data = data; + uv_queue_work(uv_default_loop(), req, EIO_Read, (uv_after_work_cb)EIO_AfterRead); +} + NAN_METHOD(Close) { // file descriptor if (!info[0]->IsInt32()) { @@ -681,6 +731,7 @@ extern "C" { Nan::SetMethod(target, "open", Open); Nan::SetMethod(target, "update", Update); Nan::SetMethod(target, "write", Write); + Nan::SetMethod(target, "read", Read); Nan::SetMethod(target, "close", Close); Nan::SetMethod(target, "list", List); Nan::SetMethod(target, "flush", Flush); diff --git a/src/serialport.h b/src/serialport.h index 07dbaf6..f0c088d 100644 --- a/src/serialport.h +++ b/src/serialport.h @@ -26,6 +26,10 @@ NAN_METHOD(Write); void EIO_Write(uv_work_t* req); void EIO_AfterWrite(uv_work_t* req); +NAN_METHOD(Read); +void EIO_Read(uv_work_t* req); +void EIO_AfterRead(uv_work_t* req); + NAN_METHOD(Close); void EIO_Close(uv_work_t* req); void EIO_AfterClose(uv_work_t* req); @@ -141,6 +145,17 @@ struct QueuedWrite { } }; +struct ReadBaton { + int fd; + char* bufferData; + size_t bufferLength; + DWORD bytesRead; + DWORD bytesToRead; + int offset; + char errorString[ERROR_STRING_SIZE]; + Nan::Callback callback; +}; + struct ListResultItem { std::string comName; std::string manufacturer; diff --git a/src/serialport_win.cpp b/src/serialport_win.cpp index 66654cf..9649203 100644 --- a/src/serialport_win.cpp +++ b/src/serialport_win.cpp @@ -155,18 +155,6 @@ void EIO_Open(uv_work_t* req) { data->result = (int)file; } -struct WatchPortBaton { - HANDLE fd; - DWORD bytesRead; - char buffer[MAX_BUFFER_SIZE]; - char errorString[ERROR_STRING_SIZE]; - DWORD errorCode; - bool disconnected; - Nan::Callback* dataCallback; - Nan::Callback* errorCallback; - Nan::Callback* disconnectedCallback; -}; - void EIO_Update(uv_work_t* req) { ConnectionOptionsBaton* data = static_cast(req->data); @@ -252,19 +240,16 @@ bool IsClosingHandle(int fd) { return false; } -void DisposeWatchPortCallbacks(WatchPortBaton* data) { - delete data->dataCallback; - delete data->errorCallback; - delete data->disconnectedCallback; -} - // FinalizerCallback will prevent WatchPortBaton::buffer from getting // collected by gc while finalizing v8::ArrayBuffer. The buffer will // get cleaned up through this callback. static void FinalizerCallback(char* data, void* hint) { uv_work_t* req = reinterpret_cast(hint); - WatchPortBaton* wpb = static_cast(req->data); - delete wpb; + ReadBaton* rb = static_cast(req->data); + if (rb->bufferData) { + delete rb->bufferData; + } + delete rb; delete req; } @@ -311,6 +296,107 @@ void EIO_Write(uv_work_t* req) { } while (data->bufferLength > data->offset); } +void EIO_Read(uv_work_t* req) { + ReadBaton* data = static_cast(req->data); + data->bytesRead = 0; + int errorCode = ERROR_SUCCESS; + if (data->bufferData == NULL) { + data->bufferData = new char[data->bufferLength]; + memset(data->bufferData, 0, data->bufferLength); + } + + char* offsetPtr = data->bufferData; + offsetPtr += data->offset; + + // Event used by GetOverlappedResult(..., TRUE) to wait for incoming data or timeout + // Event MUST be used if program has several simultaneous asynchronous operations + // on the same handle (i.e. ReadFile and WriteFile) + HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + + while (true) { + OVERLAPPED ov = {0}; + ov.hEvent = hEvent; + + // Start read operation - synchrounous or asynchronous + DWORD bytesReadSync = 0; + if (!ReadFile((HANDLE)data->fd, offsetPtr, data->bytesToRead, &bytesReadSync, &ov)) { + errorCode = GetLastError(); + if (errorCode != ERROR_IO_PENDING) { + // Read operation error + if (errorCode == ERROR_OPERATION_ABORTED) { + } else { + ErrorCodeToString("Reading from COM port (ReadFile)", errorCode, data->errorString); + CloseHandle(hEvent); + return; + } + break; + } + + // Read operation is asynchronous and is pending + // We MUST wait for operation completion before deallocation of OVERLAPPED struct + // or read data buffer + + // Wait for async read operation completion or timeout + DWORD bytesReadAsync = 0; + if (!GetOverlappedResult((HANDLE)data->fd, &ov, &bytesReadAsync, TRUE)) { + // Read operation error + errorCode = GetLastError(); + if (errorCode == ERROR_OPERATION_ABORTED) { + } else { + ErrorCodeToString("Reading from COM port (GetOverlappedResult)", errorCode, data->errorString); + CloseHandle(hEvent); + return; + } + break; + } else { + // Read operation completed asynchronously + data->bytesRead = bytesReadAsync; + } + } else { + // Read operation completed synchronously + data->bytesRead = bytesReadSync; + } + + // Return data received if any + if (data->bytesRead > 0) { + break; + } + } + + CloseHandle(hEvent); +} + +void EIO_AfterRead(uv_work_t* req) { + Nan::HandleScope scope; + bool skipCleanup = false; + ReadBaton* data = static_cast(req->data); + + v8::Local argv[3]; + + if (data->errorString[0]) { + argv[0] = Nan::Error(data->errorString); + argv[1] = argv[2] = Nan::Undefined(); + Sleep(100); // prevent the errors from occurring too fast + } else { + argv[0] = Nan::Null(); + argv[1] = Nan::New((int)data->bytesRead); + argv[2] = Nan::NewBuffer(data->bufferData, data->bufferLength, FinalizerCallback, req).ToLocalChecked(); + skipCleanup = true; + } + + data->callback.Call(3, argv); + +cleanup: + if (!skipCleanup) { + if (data->bufferData) { + delete data->bufferData; + } + delete data; + delete req; + } +} + + void EIO_Close(uv_work_t* req) { VoidBaton* data = static_cast(req->data); From 72768179df53a6e47b6fb7dfff31ea229e4a505a Mon Sep 17 00:00:00 2001 From: Munyiri Kamau Date: Mon, 21 Nov 2016 16:30:24 -0800 Subject: [PATCH 2/3] Fix build and test issues + updates based on review feedback - Fix CI failure to build - Tests (including read) now pass locally - Changes based on review feedback --- src/serialport.cpp | 30 ++++++++++++++++++++++---- src/serialport.h | 10 ++++++--- src/serialport_win.cpp | 48 ------------------------------------------ 3 files changed, 33 insertions(+), 55 deletions(-) diff --git a/src/serialport.cpp b/src/serialport.cpp index 3b25d4d..e85c2b7 100644 --- a/src/serialport.cpp +++ b/src/serialport.cpp @@ -336,6 +336,7 @@ void EIO_AfterWrite(uv_work_t* req) { delete queuedWrite; } +#ifdef WIN32 NAN_METHOD(Read) { // file descriptor if (!info[0]->IsInt32()) { @@ -349,9 +350,6 @@ NAN_METHOD(Read) { Nan::ThrowTypeError("Second argument must be a buffer"); return; } - v8::Local buffer = info[1]->ToObject(); - char* bufferData = node::Buffer::Data(buffer); - size_t bufferLength = node::Buffer::Length(buffer); // offset if (!info[2]->IsInt32()) { @@ -378,7 +376,8 @@ NAN_METHOD(Read) { data->fd = fd; data->offset = offset; data->bytesToRead = bytesToRead; - data->bufferLength = bufferLength; + v8::Local buffer = info[1]->ToObject(); + data->bufferData = node::Buffer::Data(buffer); data->callback.Reset(info[4].As()); uv_work_t* req = new uv_work_t(); @@ -386,6 +385,27 @@ NAN_METHOD(Read) { uv_queue_work(uv_default_loop(), req, EIO_Read, (uv_after_work_cb)EIO_AfterRead); } +void EIO_AfterRead(uv_work_t* req) { + Nan::HandleScope scope; + ReadBaton* data = static_cast(req->data); + + v8::Local argv[2]; + + if (data->errorString[0]) { + argv[0] = Nan::Error(data->errorString); + argv[1] = Nan::Undefined(); + } else { + argv[0] = Nan::Null(); + argv[1] = Nan::New((int)data->bytesRead); + } + + data->callback.Call(2, argv); + + delete data; + delete req; +} +#endif + NAN_METHOD(Close) { // file descriptor if (!info[0]->IsInt32()) { @@ -731,7 +751,9 @@ extern "C" { Nan::SetMethod(target, "open", Open); Nan::SetMethod(target, "update", Update); Nan::SetMethod(target, "write", Write); +#ifdef WIN32 Nan::SetMethod(target, "read", Read); +#endif Nan::SetMethod(target, "close", Close); Nan::SetMethod(target, "list", List); Nan::SetMethod(target, "flush", Flush); diff --git a/src/serialport.h b/src/serialport.h index f0c088d..e89cff9 100644 --- a/src/serialport.h +++ b/src/serialport.h @@ -26,9 +26,11 @@ NAN_METHOD(Write); void EIO_Write(uv_work_t* req); void EIO_AfterWrite(uv_work_t* req); +#ifdef WIN32 NAN_METHOD(Read); void EIO_Read(uv_work_t* req); void EIO_AfterRead(uv_work_t* req); +#endif NAN_METHOD(Close); void EIO_Close(uv_work_t* req); @@ -145,16 +147,18 @@ struct QueuedWrite { } }; +#ifdef WIN32 struct ReadBaton { int fd; char* bufferData; size_t bufferLength; - DWORD bytesRead; - DWORD bytesToRead; - int offset; + size_t bytesRead; + size_t bytesToRead; + size_t offset; char errorString[ERROR_STRING_SIZE]; Nan::Callback callback; }; +#endif struct ListResultItem { std::string comName; diff --git a/src/serialport_win.cpp b/src/serialport_win.cpp index 9649203..5a3dedb 100644 --- a/src/serialport_win.cpp +++ b/src/serialport_win.cpp @@ -240,19 +240,6 @@ bool IsClosingHandle(int fd) { return false; } -// FinalizerCallback will prevent WatchPortBaton::buffer from getting -// collected by gc while finalizing v8::ArrayBuffer. The buffer will -// get cleaned up through this callback. -static void FinalizerCallback(char* data, void* hint) { - uv_work_t* req = reinterpret_cast(hint); - ReadBaton* rb = static_cast(req->data); - if (rb->bufferData) { - delete rb->bufferData; - } - delete rb; - delete req; -} - void EIO_Write(uv_work_t* req) { QueuedWrite* queuedWrite = static_cast(req->data); WriteBaton* data = static_cast(queuedWrite->baton); @@ -300,10 +287,6 @@ void EIO_Read(uv_work_t* req) { ReadBaton* data = static_cast(req->data); data->bytesRead = 0; int errorCode = ERROR_SUCCESS; - if (data->bufferData == NULL) { - data->bufferData = new char[data->bufferLength]; - memset(data->bufferData, 0, data->bufferLength); - } char* offsetPtr = data->bufferData; offsetPtr += data->offset; @@ -366,37 +349,6 @@ void EIO_Read(uv_work_t* req) { CloseHandle(hEvent); } -void EIO_AfterRead(uv_work_t* req) { - Nan::HandleScope scope; - bool skipCleanup = false; - ReadBaton* data = static_cast(req->data); - - v8::Local argv[3]; - - if (data->errorString[0]) { - argv[0] = Nan::Error(data->errorString); - argv[1] = argv[2] = Nan::Undefined(); - Sleep(100); // prevent the errors from occurring too fast - } else { - argv[0] = Nan::Null(); - argv[1] = Nan::New((int)data->bytesRead); - argv[2] = Nan::NewBuffer(data->bufferData, data->bufferLength, FinalizerCallback, req).ToLocalChecked(); - skipCleanup = true; - } - - data->callback.Call(3, argv); - -cleanup: - if (!skipCleanup) { - if (data->bufferData) { - delete data->bufferData; - } - delete data; - delete req; - } -} - - void EIO_Close(uv_work_t* req) { VoidBaton* data = static_cast(req->data); From 91d7f4a55c821680e7b953f683899b825361ea09 Mon Sep 17 00:00:00 2001 From: Munyiri Kamau Date: Mon, 21 Nov 2016 19:11:04 -0800 Subject: [PATCH 3/3] Remove space before function parentheses --- lib/bindings-win32.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/bindings-win32.js b/lib/bindings-win32.js index 8f809cc..8d2a291 100644 --- a/lib/bindings-win32.js +++ b/lib/bindings-win32.js @@ -19,7 +19,7 @@ function WindowsBinding(opt) { this.fd = null; }; -WindowsBinding.prototype.read = function (buffer, offset, length, cb) { +WindowsBinding.prototype.read = function(buffer, offset, length, cb) { if (!Buffer.isBuffer(buffer)) { throw new TypeError('"buffer" is not a Buffer'); }