From bb39e64e2cdd43dcc3bde1d35548e1bcb114fef4 Mon Sep 17 00:00:00 2001 From: Matheus Sampaio Date: Thu, 13 Jul 2017 10:10:57 -0300 Subject: [PATCH] feat: add readbytedata method --- lib/i2c.coffee | 6 ++++++ src/i2c.cc | 28 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/lib/i2c.coffee b/lib/i2c.coffee index cb0ddbb..b612fc6 100644 --- a/lib/i2c.coffee +++ b/lib/i2c.coffee @@ -78,6 +78,12 @@ class i2c extends EventEmitter tick -> callback err, data + readByteData: (position, callback) -> + @setAddress @address + wire.readByteData position, (err, data) -> + tick -> + callback err, data + readBytes: (cmd, len, callback) -> @setAddress @address wire.readBlock cmd, len, null, (err, actualBuffer) -> diff --git a/src/i2c.cc b/src/i2c.cc index c7d4bee..cf51e78 100644 --- a/src/i2c.cc +++ b/src/i2c.cc @@ -148,6 +148,32 @@ void ReadByte(const Nan::FunctionCallbackInfo& info) { info.GetReturnValue().Set(data); } +void ReadByteData(const Nan::FunctionCallbackInfo& info) { + Nan::HandleScope scope; + + Local data; + Local err = Nan::New(Nan::Null()); + + int32_t position = info[0]->Int32Value(); + + int32_t res = i2c_smbus_read_byte_data(fd, position); + + if (res == -1) { + err = Nan::Error(Nan::New("Cannot read device").ToLocalChecked()); + } else { + data = Nan::New(res); + } + + if (info[1]->IsFunction()) { + const unsigned argc = 2; + Local callback = Local::Cast(info[1]); + Local argv[argc] = { err, data }; + Nan::MakeCallback(Nan::GetCurrentContext()->Global(), callback, argc, argv); + } + + info.GetReturnValue().Set(data); +} + void ReadBlock(const Nan::FunctionCallbackInfo& info) { Nan::HandleScope scope; @@ -287,6 +313,8 @@ void Init(Handle exports) { Nan::New(Read)->GetFunction()); exports->Set(Nan::New("readByte").ToLocalChecked(), Nan::New(ReadByte)->GetFunction()); + exports->Set(Nan::New("readByteData").ToLocalChecked(), + Nan::New(ReadByteData)->GetFunction()); exports->Set(Nan::New("readBlock").ToLocalChecked(), Nan::New(ReadBlock)->GetFunction());