1#!/usr/bin/env node 2 3/* 4server.js - <short description TODO> 5Copyright (C) 2022 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/osc/server.js> 6This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. 7*/ 8 9// import OSC from 'osc-js'; 10 11import { WebSocketServer } from 'ws'; 12import osc from 'osc'; 13 14const WS_PORT = 8080; // WebSocket server port 15const OSC_REMOTE_IP = '127.0.0.1'; 16const OSC_REMOTE_PORT = 57120; 17 18const udpPort = new osc.UDPPort({ 19 localAddress: '0.0.0.0', 20 localPort: 0, 21 remoteAddress: OSC_REMOTE_IP, 22 remotePort: OSC_REMOTE_PORT, 23}); 24 25udpPort.open(); 26console.log(`[Sending OSC] ${OSC_REMOTE_IP}:${OSC_REMOTE_PORT}`); 27 28udpPort.on('error', (e) => { 29 console.log('Error: ', e); 30}); 31 32const wss = new WebSocketServer({ port: WS_PORT }); 33console.log(`[Listening WS] ws://localhost:${WS_PORT}`); 34 35wss.on('connection', (ws) => { 36 console.log('New WebSocket connection'); 37 38 ws.on('message', (message) => { 39 let osc_host = '127.0.0.1'; 40 let osc_port = 57120; 41 42 try { 43 const data = JSON.parse(message); 44 if ('host' in data) { 45 osc_host = data['host']; 46 } 47 if ('port' in data) { 48 osc_port = data['port']; 49 } 50 let msg = { address: data['address'], args: data['args'] }; 51 if ('timestamp' in data) { 52 msg = { timeTag: osc.timeTag(0, data['timestamp']), packets: [msg] }; 53 } 54 55 udpPort.send(msg, osc_host, osc_port); 56 } catch (err) { 57 console.error('Error parsing message:', err); 58 } 59 }); 60 61 ws.on('close', () => { 62 console.log('WebSocket connection closed'); 63 }); 64});