Skip to content

Commit

Permalink
test(example): add example CommWeb base nodejs bindings
Browse files Browse the repository at this point in the history
  • Loading branch information
itas109 committed Jun 23, 2024
1 parent da80e87 commit 2ab17b7
Show file tree
Hide file tree
Showing 9 changed files with 569 additions and 0 deletions.
53 changes: 53 additions & 0 deletions examples/CommWeb/.vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "node launch",
"program": "${workspaceFolder}/index.js",
"env": {},
"skipFiles": [
"<node_internals>/**"
]
},
{
"name": "windows cpp launch",
"type": "cppvsdbg",
"request": "launch",
"program": "C:/Program Files/nodejs/node.exe",
"args": [
"${workspaceFolder}/index.js"
],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"console": "externalTerminal"
},
{
"name": "linux cpp launch",
"type": "cppdbg",
"request": "launch",
"program": "/usr/local/bin/node",
"args": [
"${workspaceFolder}/index.js"
],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "enable pretty printing",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
74 changes: 74 additions & 0 deletions examples/CommWeb/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
{
"files.associations": {
"vector": "cpp",
"xstring": "cpp",
"xutility": "cpp",
"iostream": "cpp",
"thread": "cpp",
"algorithm": "cpp",
"atomic": "cpp",
"bit": "cpp",
"cctype": "cpp",
"charconv": "cpp",
"chrono": "cpp",
"clocale": "cpp",
"cmath": "cpp",
"compare": "cpp",
"concepts": "cpp",
"cstddef": "cpp",
"cstdint": "cpp",
"cstdio": "cpp",
"cstdlib": "cpp",
"cstring": "cpp",
"ctime": "cpp",
"cwchar": "cpp",
"exception": "cpp",
"format": "cpp",
"forward_list": "cpp",
"functional": "cpp",
"initializer_list": "cpp",
"iomanip": "cpp",
"ios": "cpp",
"iosfwd": "cpp",
"istream": "cpp",
"iterator": "cpp",
"limits": "cpp",
"list": "cpp",
"locale": "cpp",
"memory": "cpp",
"mutex": "cpp",
"new": "cpp",
"optional": "cpp",
"ostream": "cpp",
"ratio": "cpp",
"sstream": "cpp",
"stdexcept": "cpp",
"stop_token": "cpp",
"streambuf": "cpp",
"string": "cpp",
"system_error": "cpp",
"tuple": "cpp",
"type_traits": "cpp",
"typeinfo": "cpp",
"unordered_map": "cpp",
"utility": "cpp",
"xfacet": "cpp",
"xhash": "cpp",
"xiosbase": "cpp",
"xlocale": "cpp",
"xlocbuf": "cpp",
"xlocinfo": "cpp",
"xlocmes": "cpp",
"xlocmon": "cpp",
"xlocnum": "cpp",
"xloctime": "cpp",
"xmemory": "cpp",
"xtr1common": "cpp",
"array": "cpp",
"deque": "cpp",
"queue": "cpp",
"ranges": "cpp",
"span": "cpp",
"condition_variable": "cpp"
}
}
59 changes: 59 additions & 0 deletions examples/CommWeb/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
#***************************************************************************
# @file CMakeLists.txt
# @author itas109 ([email protected]) \n\n
# Blog : https://blog.csdn.net/itas109 \n
# Github : https://github.com/itas109 \n
# Gitee : https://gitee.com/itas109 \n
# QQ Group : 129518033
# @brief Lightweight cross-platform serial port library based on C++
# @copyright The CSerialPort is Copyright (C) 2014 itas109 <[email protected]>.
# You may use, copy, modify, and distribute the CSerialPort, under the terms
# of the LICENSE file.
############################################################################
cmake_minimum_required(VERSION 2.8.12)

project(cserialport)

# add_definitions(-DCSERIALPORT_DEBUG) # CSerialPort Debug Mode

set(CMAKE_CXX_STANDARD 11)
#add_compile_options(-g)

include_directories(${CMAKE_JS_INC})
include_directories(.)

# Include N-API wrappers
include_directories(node-addon-api)

# cserialport files
set(CSerialPortRootPath "${CMAKE_CURRENT_SOURCE_DIR}/../..")
include_directories(${CSerialPortRootPath}/include)
list(APPEND CSerialPortSourceFiles ${CSerialPortRootPath}/src/SerialPort.cpp ${CSerialPortRootPath}/src/SerialPortBase.cpp ${CSerialPortRootPath}/src/SerialPortInfo.cpp ${CSerialPortRootPath}/src/SerialPortInfoBase.cpp)
if (WIN32)
list(APPEND CSerialPortSourceFiles ${CSerialPortRootPath}/src/SerialPortInfoWinBase.cpp ${CSerialPortRootPath}/src/SerialPortWinBase.cpp)
list(APPEND CSerialPortSourceFiles ${CSerialPortRootPath}/lib/version.rc)
elseif (UNIX)
list(APPEND CSerialPortSourceFiles ${CSerialPortRootPath}/src/SerialPortInfoUnixBase.cpp ${CSerialPortRootPath}/src/SerialPortUnixBase.cpp)
endif ()

# cserialport nodejs bindings files
set(CSerialPortNodeJSBindRootPath "${CMAKE_CURRENT_SOURCE_DIR}/../../bindings/nodejs")
include_directories(${CSerialPortNodeJSBindRootPath})
include_directories(${CSerialPortNodeJSBindRootPath}/node-addon-api)
list(APPEND CSerialPortNodeJSBindSourceFiles ${CSerialPortNodeJSBindRootPath}/addon.cpp ${CSerialPortNodeJSBindRootPath}/CSerialPortWrapper.cpp)

add_library(${PROJECT_NAME} SHARED ${CSerialPortNodeJSBindSourceFiles} ${CSerialPortSourceFiles} ${CMAKE_JS_SRC})

set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "" SUFFIX ".node")

target_link_libraries(${PROJECT_NAME} ${CMAKE_JS_LIB})

if (WIN32)
target_link_libraries( ${PROJECT_NAME} setupapi)
elseif(APPLE)
find_library(IOKIT_LIBRARY IOKit)
find_library(FOUNDATION_LIBRARY Foundation)
target_link_libraries( ${PROJECT_NAME} ${FOUNDATION_LIBRARY} ${IOKIT_LIBRARY})
elseif (UNIX)
target_link_libraries( ${PROJECT_NAME} pthread)
endif()
24 changes: 24 additions & 0 deletions examples/CommWeb/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# CSerialPort for Web based nodejs bindings

```
nodejs: 20.15.0 (2024-06-20)
cmake: 3.8.2
cmake-js: 7.3.0 (2024-01-16)
node-addon-api: 8.0.0 (2024-05-05)
```

## Build

```
cd bindings/nodejs
npm i -g cmake-js
npm run build
```

## Run

```
npm run start
```

open URL `http://localhost:8080`
127 changes: 127 additions & 0 deletions examples/CommWeb/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
'use strict';

const http = require('http');
const express = require('express');
const app = express();
const port = 8080;
let httpServer = http.createServer(app);

let CSerialPort;
try {
CSerialPort = require("./build/Debug/cserialport.node").CSerialPort;
} catch (error) {
CSerialPort = require("./build/Release/cserialport.node").CSerialPort;
}
const sp = new CSerialPort();
let isHex = false;

// // morgan logger dev
// const logger = require('morgan');
// app.use(logger('dev'));
// console.log('load Third-party middleware - morgan logger dev');

const path = require('path');
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function (req, res, next) {
res.send('index');
})

app.get('/pid', function (req, res, next) {
res.send(`${process.pid}`);
})

app.get('/gc', function (req, res, next) {
try {
global.gc();
res.send(JSON.stringify(process.memoryUsage()));
} catch (error) {
res.send("Please start app with --expose-gc, such as node --expose-gc index.js");
}
})

app.get('/exit', function (req, res, next) {
res.send('exit');
process.exit(0);
})

app.get('/cserialport/listPorts', function (req, res, next) {
const portInfoArray = sp.availablePortInfos();
const portInfoSize = portInfoArray.length;
let result = [];
for (let i = 1; i <= portInfoSize; i++) {
result.push(portInfoArray[i - 1].portName);
}
res.send(result);
})

app.get('/cserialport/init', function (req, res, next) {
let portName = req.query.portName;
sp.init(portName);
res.send(portName + ' init ok');
})

app.get('/cserialport/open', function (req, res, next) {
if (sp.isOpen()) {
res.send('alread open');
} else {
let result = sp.open();
res.send('open ' + result);
}
})

app.get('/cserialport/close', function (req, res, next) {
sp.close();
res.send('close ok');
})

app.get('/cserialport/isOpen', function (req, res, next) {
let result = sp.isOpen();
res.send(result);
})

app.get('/cserialport/writeData', function (req, res, next) {
let data = req.query.data;
let buffer;
if (isHex) {
buffer = Buffer.from(data); // TODO
} else {
buffer = Buffer.from(data);
}
let result = sp.writeData(buffer, buffer.length);
res.send("writeData ok. " + result);
})

app.get('/cserialport/onReadEvent', function (req, res, next) {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');

sp.onReadEvent((arrayBufferReadData) => {
if (isHex) {
res.write("data: " + arrayBufferReadData.toString('hex') + "\n\n");
} else {
res.write("data: " + arrayBufferReadData.toString() + "\n\n");
}
});

req.on('close', () => {
res.end();
});
})

app.get('/cserialport/readData/:readBufferLen', function (req, res, next) {
let readBufferLen = req.params.readBufferLen;
readBufferLen = readBufferLen > 0 ? readBufferLen : 1;
let buffer = Buffer.alloc(readBufferLen);
sp.readData(buffer, buffer.length);
if (isHex) {
res.send(buffer.toString());
} else {
res.send(buffer.toString('hex'));
}
})

httpServer.listen(port);

console.log('http://localhost:' + port);
13 changes: 13 additions & 0 deletions examples/CommWeb/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"name": "cserialport",
"version": "1.0.0",
"description": "Node.js CSerialPort Web Example",
"main": "index.js",
"dependencies": {
"express": "^4.19.2"
},
"scripts": {
"build": "cmake-js rebuild",
"start": "node index.js"
}
}
Loading

0 comments on commit 2ab17b7

Please sign in to comment.