re-emerge code from before.

This commit is contained in:
Chris Williams 2010-09-19 17:55:25 -04:00
parent 9ef351e611
commit 9e105e007c
3 changed files with 178 additions and 249 deletions

87
serialport.js Normal file
View file

@ -0,0 +1,87 @@
"use strict";
/*global process require exports console */
var sys = require('sys'),
Buffer = require('buffer').Buffer,
events = require('events'),
fs = require('fs'),
serialport_native = require('./serialport_native');
var BAUDRATES = [115200, 57600, 38400, 19200, 9600, 4800, 2400, 1800, 120,, 600, 300, 200, 150, 134, 110, 75, 50];
var DATABITS = [8, 7, 6, 5];
var STOPBITS = [1, 2];
var PARITY = [0, 1, 2];
// can accept path, baudrate, databits, stopbits, parity
function SerialPort(path) {
var me = this;
events.EventEmitter.call(this);
this.active = false;
this.baudrate = 38400;
this.databits = 8;
this.stopbits = 1;
this.parity = 0;
if (arguments.length >= 2 && BAUDRATES.indexOf(arguments[1]) >= 0) {
this.baudrate = arguments[1];
}
if (arguments.length >= 3 && DATABITS.indexOf(arguments[2]) >= 0) {
this.databits = arguments[2];
}
if (arguments.length >= 4 && STOPBITS.indexOf(arguments[3]) >= 0) {
this.stopbits = arguments[3];
}
if (arguments.length >= 5 && PARITY.indexOf(arguments[4]) >= 0) {
this.parity = arguments[4];
}
this.fd = serialport_native.open(path, baudrate, databits, stopbits, parity);
this.active = true;
this.readWatcher = new process.IOWatcher();
this.empty_reads = 0;
this.buf = new Buffer(65535);
function data_ready(header) {
header.link_type = me.link_type;
header.time_ms = (header.tv_sec * 1000) + (header.tv_usec / 1000);
me.buf.pcap_header = header;
me.emit('data', me.buf);
}
// readWatcher gets a callback when pcap has data to read. multiple packets may be readable.
this.readWatcher.callback = function pcap_read_callback() {
var packets_read = binding.dispatch(me.buf, packet_ready);
if (packets_read < 1) {
// TODO - figure out what is causing this, and if it is bad.
me.empty_reads += 1;
}
};
this.readWatcher.set(this.fd, true, false);
this.readWatcher.start();
}
sys.inherits(SerialPort, events.EventEmitter);
SerialPort.prototype.close = function () {
if (this.active) {
this.active = false;
fs.close(this.fd);
this.readWatcher.stop();
}
};
SerialPort.prototype.write = function (buffer) {
fs.write(this.fd);
}
exports.SerialPort = SerialPort;

View file

@ -18,55 +18,79 @@
#include <sys/types.h>
#include <node.h>
#include <node_events.h>
#include <node_buffer.h>
#include <v8.h>
using namespace v8;
using namespace node;
#define THROW_BAD_ARGS ThrowException(Exception::TypeError(String::New("Bad argument")))
namespace node {
static Persistent<String> data_symbol;
static Persistent<String> close_symbol;
using namespace v8;
class SerialPort : public EventEmitter {
public:
static void
Initialize (v8::Handle<v8::Object> target)
{
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(New);
t->Inherit(EventEmitter::constructor_template);
t->InstanceTemplate()->SetInternalFieldCount(1);
data_symbol = NODE_PSYMBOL("data");
close_symbol = NODE_PSYMBOL("close");
NODE_SET_PROTOTYPE_METHOD(t, "open", Open);
NODE_SET_PROTOTYPE_METHOD(t, "close", Close);
NODE_SET_PROTOTYPE_METHOD(t, "write", Write);
target->Set(String::NewSymbol("SerialPort"), t->GetFunction());
static inline Local<Value> errno_exception(int errorno) {
Local<Value> e = Exception::Error(String::NewSymbol(strerror(errorno)));
Local<Object> obj = e->ToObject();
obj->Set(NODE_PSYMBOL("errno"), Integer::New(errorno));
return e;
}
bool Open(const char* path, int baudrate, int databits, int stopbits, int parity) {
if (fd_) return false;
static Handle<Value> Open(const Arguments& args) {
HandleScope scope;
struct termios newtio;
long Baud_Rate = 38400;
int Data_Bits = 8;
int Stop_Bits = 1;
int Parity = 0;
long BAUD;
long DATABITS;
long STOPBITS;
long PARITYON;
long PARITY;
if (!args[0]->IsString()) {
return scope.Close(THROW_BAD_ARGS);
}
// Baud Rate Argument
if (args.Length() >= 2 && !args[1]->IsInt32()) {
return scope.Close(THROW_BAD_ARGS);
} else {
Baud_Rate = args[1]->Int32Value();
}
switch (baudrate)
// Data Bits Argument
if (args.Length() >= 3 && !args[2]->IsInt32()) {
return scope.Close(THROW_BAD_ARGS);
} else {
Data_Bits = args[2]->Int32Value();
}
// Stop Bits Arguments
if (args.Length() >= 4 && !args[3]->IsInt32()) {
return scope.Close(THROW_BAD_ARGS);
} else {
Stop_Bits = args[2]->Int32Value();
}
// Parity Arguments
if (args.Length() >= 5 && !args[4]->IsInt32()) {
return scope.Close(THROW_BAD_ARGS);
} else {
Parity = args[2]->Int32Value();
}
switch (Baud_Rate)
{
case 38400:
default:
@ -115,8 +139,8 @@ public:
BAUD = B50;
break;
}
switch (databits)
switch (Data_Bits)
{
case 8:
default:
@ -132,7 +156,7 @@ public:
DATABITS = CS5;
break;
}
switch (stopbits)
switch (Stop_Bits)
{
case 1:
default:
@ -144,7 +168,7 @@ public:
}
switch (parity)
switch (Parity)
{
case 0:
default: //none
@ -161,24 +185,24 @@ public:
break;
}
int flags = (O_RDWR | O_NOCTTY | O_NONBLOCK);
fd_ = open(path, flags);
if (fd_ < 0) return false;
String::Utf8Value path(args[0]->ToString());
int flags = (O_RDWR | O_NOCTTY | O_NONBLOCK);
int fd = open(*path, flags);
if (fd < 0) return scope.Close(ThrowException(errno_exception(errno)));
struct sigaction saio;
// TODO: Hook event emitter to signal handler
saio.sa_handler = SIG_IGN;
// ENDTODO
sigemptyset(&saio.sa_mask); //saio.sa_mask = 0;
saio.sa_flags = 0;
// saio.sa_restorer = NULL;
sigaction(SIGIO,&saio,NULL);
//all process to receive SIGIO
fcntl(fd_, F_SETOWN, getpid());
fcntl(fd_, F_SETFL, FASYNC);
fcntl(fd, F_SETOWN, getpid());
fcntl(fd, F_SETFL, FASYNC);
newtio.c_cflag = BAUD | CRTSCTS | DATABITS | STOPBITS | PARITYON | PARITY | CLOCAL | CREAD;
@ -187,203 +211,34 @@ public:
newtio.c_lflag = 0; //ICANON;
newtio.c_cc[VMIN]=1;
newtio.c_cc[VTIME]=0;
tcflush(fd_, TCIFLUSH);
tcsetattr(fd_,TCSANOW,&newtio);
tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&newtio);
Ref();
return true;
return scope.Close(Integer::New(fd));
}
int Write(char* buf, size_t length) {
size_t written = write(fd_, buf, length);
return written;
}
void Close (Local<Value> exception = Local<Value>())
{
void SerialPort::Initialize(Handle<Object> target) {
HandleScope scope;
if (fd_) {
close(fd_);
fd_ = NULL;
}
Emit(close_symbol, 0, NULL);
Unref();
NODE_SET_METHOD(target, "open", Open);
}
protected:
static Handle<Value>
New (const Arguments& args)
{
HandleScope scope;
SerialPort *serial_port = new SerialPort();
serial_port->Wrap(args.This());
return scope.Close(args.This());
}
static Handle<Value>
Write (const Arguments& args)
{
HandleScope scope;
SerialPort *serial_port = ObjectWrap::Unwrap<SerialPort>(args.This());
int written = 0;
if (args[0]->IsString()) {
String::Utf8Value buffer(args[0]->ToString());
written = serial_port->Write(*buffer, buffer.length());
} else if (Buffer::HasInstance(args[0])) {
Buffer * buffer = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject());
size_t buffer_length = buffer->length();
char * buf = (char*)buffer->data();
if (buffer_length < 0) {
return ThrowException(Exception::TypeError(String::New("Bad argument")));
}
written = serial_port->Write(buf, buffer_length);
} else {
return scope.Close(ThrowException(Exception::Error(String::New("First argument must be a string or buffer."))));
}
if (written < 0) return ThrowException(Exception::Error(String::NewSymbol(strerror(errno))));
return scope.Close(Integer::New(written));
}
static Handle<Value>
Open (const Arguments& args)
{
HandleScope scope;
SerialPort *serial_port = ObjectWrap::Unwrap<SerialPort>(args.This());
long baudrate = 38400;
int databits = 8;
int stopbits = 1;
int parity = 0;
if (!args[0]->IsString()) {
return scope.Close(ThrowException(Exception::Error(String::New("Must give serial device string as argument"))));
}
String::Utf8Value path(args[0]->ToString());
// Baud Rate Argument
if (args.Length() >= 2 && !args[1]->IsInt32()) {
return scope.Close(ThrowException(Exception::Error(
String::New("If giving baud rate, must be a integer value."))));
} else {
baudrate = args[1]->Int32Value();
}
// Data Bits Argument
if (args.Length() >= 3 && !args[2]->IsInt32()) {
return scope.Close(ThrowException(Exception::Error(
String::New("If giving data bits, must be a integer value."))));
} else {
databits = args[2]->Int32Value();
}
// Stop Bits Arguments
if (args.Length() >= 4 && !args[3]->IsInt32()) {
return scope.Close(ThrowException(Exception::Error(
String::New("If giving stop bits, must be a integer value."))));
} else {
stopbits = args[3]->Int32Value();
}
// parity Arguments
if (args.Length() >= 5 && !args[4]->IsInt32()) {
return scope.Close(ThrowException(Exception::Error(
String::New("If giving parity, must be a integer value."))));
} else {
parity = args[4]->Int32Value();
}
bool r = serial_port->Open(*path, baudrate, databits, stopbits, parity);
if (!r) {
return ThrowException(Exception::Error(
String::New("Could not open serial port.")));
}
return scope.Close(Undefined());
}
static Handle<Value>
Close (const Arguments& args)
{
SerialPort *serial_port = ObjectWrap::Unwrap<SerialPort>(args.This());
HandleScope scope;
serial_port->Close();
return scope.Close(Undefined());
}
SerialPort () : EventEmitter ()
{
fd_ = NULL;
ev_init(&read_watcher_, io_event);
read_watcher_.data = this;
ev_init(&write_watcher_, io_event);
write_watcher_.data = this;
}
~SerialPort ()
{
if(fd_) {
close(fd_);
fd_ = NULL;
}
}
private:
void Event (int revents)
{
if (revents & EV_ERROR) {
printf("EV_ERROR");
return;
}
if (revents & EV_READ) {
Emit(data_symbol, 0, NULL);
return;
}
}
static void
io_event (EV_P_ ev_io *w, int revents)
{
SerialPort *serial_port = static_cast<SerialPort*>(w->data);
serial_port->Event(revents);
}
int fd_;
ev_io read_watcher_;
ev_io write_watcher_;
};
extern "C" void
init (Handle<Object> target)
{
HandleScope scope;
SerialPort::Initialize(target);
}
extern "C" void
init (Handle<Object> target)
{
HandleScope scope;
SerialPort::Initialize(target);
}
}
//-------------

21
test.js
View file

@ -1,22 +1,9 @@
var sys = require("sys");
var fs = require("fs");
var SerialPort = require("./serialport_native").SerialPort;
sp = new SerialPort;
sp.open("./sampleport");
var str = "TEST";
sp.write(str);
var buf = new Buffer([0x02, 0x03, 0x05, 0x02, 0x01]);
sp.write(buf);
var fd = SerialPort.open("./sampleport");
fs.close(fd);
sp.close();
/*
sp.on("data", function(resp) {
});
sp.write(sp, "Test", "utf8");
sp.close(sp);
*/
// sys.puts(sp);
// fs.write(sp, "test", null, "utf8");