【Websocket X IoT】Node.js上でWebsocketネットワークを構築し、ラズパイ&Arduinoをシリアル通信でデータを受信してみる
※ 当ページには【広告/PR】を含む場合があります。
2021/06/13
ネットワークに接続できる
websokect-nodeのインストール
$ npm install websocket serialport
Websocketサーバーのテスト
server.js
const webSocketsServerPort = 41337;
const webSocketServer = require('websocket').server;
const http = require('http');
const server = http.createServer((request, response) => {
// Not important for us.
// We're writing WebSocket server, not HTTP server
});
const clients = [];
server.listen(webSocketsServerPort, () => {
console.log((new Date()) + " Server is listening on port " + webSocketsServerPort);
});
const wsServer = new webSocketServer({httpServer: server});
// Event if the server recieved a request from a listed client
wsServer.on('request', (request) => {
console.log((new Date()) + ' Connection from origin ' + request.origin + '.');
const connection = request.accept(null, request.origin);
console.log((new Date()) + ' Connection accepted.');
const index = clients.push(connection) - 1;
// Event when the server recieved message from clients
connection.on('message', (message) => {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
} else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
}
});
// Event when an user disconnected
connection.on('close', (connection) => {
console.log((new Date()) + " Peer " + connection.remoteAddress + " disconnected.");
// Remove an user from the list of connected clients
clients.splice(index, 1);
});
});
$ node server.js
Wed Jun 09 2021 02:54:08 GMT+0000 (Coordinated Universal Time) Server is listening on port 41337
Websocketサーバーのレスポンステスト
$ curl -o - --http1.1 --include \
--no-buffer \
--header "Connection: Upgrade" \
--header "Upgrade: websocket" \
--header "Host: 192.168.0.123:41337" \
--header "Origin: http://192.168.0.123:41337" \
--header "Sec-WebSocket-Key: SGVsbG8sIHdvcmxkIQ==" \
--header "Sec-WebSocket-Version: 13" \
http://192.168.0.123:41337/
#👇レスポンス
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: qGEgH3En71di5rrssAZTmtRTyFk=
Origin: http://192.168.0.123:41337
�
$ node server.js
Wed Jun 09 2021 02:54:08 GMT+0000 (Coordinated Universal Time) Server is listening on port 41337
Wed Jun 09 2021 02:54:21 GMT+0000 (Coordinated Universal Time) Connection from origin http://192.168.0.123:41337.
Wed Jun 09 2021 02:54:21 GMT+0000 (Coordinated Universal Time) Connection accepted.
Wed Jun 09 2021 02:54:41 GMT+0000 (Coordinated Universal Time) Peer undefined disconnected.
WebsocketサーバーとSerialportの連結
server.js
const webSocketsServerPort = 41337;
const webSocketServer = require('websocket').server;
const http = require('http');
const server = http.createServer((request, response) => {});
const clients = [];
server.listen(webSocketsServerPort, () => {
console.log((new Date()) + " Server is listening on port " + webSocketsServerPort);
});
const wsServer = new webSocketServer({httpServer: server});
//👇シリアル通信用のライブラリ読み込み
const SerialPort = require('serialport');
const Readline = require('@serialport/parser-readline');
//👇ゲスト上(Arduino側)のSerialデバイスに名前を合せる
const portName = '/dev/ttyUSB0';
//👇接続先(Arduino)のシリアルモデムを考慮
const sp = new SerialPort(portName, {
baudRate: 9600,
dataBits: 8,
parity: 'none',
stopBits: 1,
flowControl: false,
});
//👇パーサクラスを指定
const parser = sp.pipe(new Readline());
// Event if the server recieved a request from a listed client
wsServer.on('request', (request) => {
console.log((new Date()) + ' Connection from origin ' + request.origin + '.');
const connection = request.accept(null, request.origin);
console.log((new Date()) + ' Connection accepted.');
const index = clients.push(connection) - 1;
// Event when the server recieved message from clients
connection.on('message', (message) => {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
//👇クライアントから受け取った文字列をデバイスへリダイレクト
sp.write(message.utf8Data, (err) => {
if (err) {
return console.log('Error: ', err.message);
}
console.log('Utf8 data written over uart.');
})
} else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
//👇クライアントから受け取ったバイナリをデバイスへリダイレクト
sp.write(message.binaryData, (err) => {
if (err) {
return console.log('Error: ', err.message);
}
console.log('Byte data written over uart.');
})
}
});
// Event when an user disconnected
connection.on('close', (connection) => {
console.log((new Date()) + " Peer " + connection.remoteAddress + " disconnected.");
// Remove an user from the list of connected clients
clients.splice(index, 1);
});
});
//👇ポート開放時の初期化処理
sp.on('open', ()=> {
console.log('Open Serialport');
});
//👇データ(Arduino > ラズパイ)の受信
parser.on('data', (inp_) => {
try {
console.log(`Uart Msg: ${inp_}`);
for (let i=0; i < clients.length; i++) {
//👇接続中のすべてのwsクライアントへメッセージ送信
clients[i].sendUTF(`Uart Msg: ${inp_}`);
};
} catch(e) {
return;
}
});
$ node server.js
Sun Jun 13 2021 05:26:13 GMT+0000 (Coordinated Universal Time) Server is listening on port 41337
Open Serialport
Uart Msg: LED ON
Uart Msg: LED OFF
Uart Msg: LED ON
Uart Msg: LED OFF
Uart Msg: LED ON
#...以下略
Websocketクライアントの実装
①WebsocketAPIを使う
192.168.0.123:41337
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#display {
width: 500px;
height: 100px;
font-size: 2em;
}
</style>
</head>
<body>
<textarea id="display"></textarea>
<script>
const ws = new WebSocket('ws://192.168.0.248:41337');
const display = document.getElementById('display');
let currentData = {};
ws.onmessage = (event) => {display.value = `${event.data}`;}
</script>
</body>
</html>
②Nodejsネイティブで使う
client.js
const WebSocketClient = require('websocket').client;
const client = new WebSocketClient();
//👇接続エラー時のイベント
client.on('connectFailed', (err) => {
console.log('Connect Error: ' + err.toString());
});
//👇接続中のイベント
client.on('connect', (connection) => {
console.log('WebSocket Client Connected...');
//👇接続時のエラー
connection.on('error', (err) => {
console.log("Connection Error: " + err.toString());
});
//👇サーバーからのメッセージ受信時
connection.on('message', (message) => {
if (message.type === 'utf8') {
console.log(`Received UTF8: ${message.utf8Data}`);
} else if (message.type === 'binary') {
console.log(`Received Binary: ${message.binaryData.length} Bytes`);
}
});
//👇切断時のイベント
connection.on('close', () => {
console.log('Client Connection Closed');
});
});
client.connect('ws://192.168.0.123:41337/');
node client.js
まとめ
参考サイト
記事を書いた人
ナンデモ系エンジニア
電子工作を身近に知っていただけるように、材料調達からDIYのハウツーまで気になったところをできるだけ細かく記事にしてブログ配信してます。
カテゴリー