const express = require('express') const http = require('http') const WebSocket = require('ws') const osc = require('osc') const port = 6676 // Vzemi iz argumenta const tty = process.argv[2] const include_files = [ '/anim.js', '/control.js', '/test.js', '/node_modules/three/build/three.min.js', '/node_modules/nouislider/distribute/nouislider.min.js', '/node_modules/nouislider/distribute/nouislider.min.css', '/node_modules/osc/dist/osc-browser.js' ]; const app = express(); const server = http.Server(app); // Odprti serijski OSC link const scon = new osc.SerialPort({ devicePath: tty, bitrate: 115200 }) scon.on('error', e => { console.log('tty error', e) }) scon.open() app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); app.get('/ctl', (req, res) => { res.sendFile(__dirname + '/control.html'); }); app.get('/test', (req, res) => { res.sendFile(__dirname + '/test.html'); }); let settings = {}; app.get('/settings', function(req, res) { res.send(settings); }); include_files.map(function(file) { app.get(file, function(req, res){ res.sendFile(__dirname + file); }); }); server.listen(port, () => console.log('listening on *:' + port)) // Websocket init const wss = new WebSocket.Server({ server }) const sendAll = (msg, wss, ws = null) => { wss.clients.forEach( client => { if (client != ws) { client.send(msg) } }) } // Debug osc /* scon.on('osc', msg => { console.log('tty osc', msg.address, ...msg.args.map(val => Math.round(val * 1000) / 1000)) }) */ wss.on('connection', function (ws) { const oscWS = new osc.WebSocketPort({ socket: ws, metadata: true }); // Arduino OSC gre v web scon.on('osc', msg => { switch(msg.address) { case '/gyro/': const [gx, gy, gz] = msg.args sendAll('adjust:rotx:' + gx, wss) sendAll('adjust:roty:' + gy, wss) sendAll('adjust:rotz:' + gz, wss) break; case '/quaternion/': const [qw, qx, qy, qz] = msg.args sendAll('adjust:quaternion:' + [qw, qx, qy, qz].join(':'), wss) break; case '/accel/': const [ax, ay, az] = msg.args sendAll('adjust:posx:' + ax, wss) sendAll('adjust:posy:' + ay, wss) sendAll('adjust:posz:' + az, wss) break; } }) ws.on('message', (msg) => { //console.log('got msg', msg) const parts = msg.split(":") const cmd = parts[0] // Broadcast adjust msg switch (cmd) { case 'adjust': sendAll(msg, wss, ws) } }) })