Code coverage report for osc/transport.js

Statements: 95.28% (121 / 127)      Branches: 84.21% (32 / 38)      Functions: 100% (20 / 20)      Lines: 97.32% (109 / 112)      Ignored: none     

All files » osc/ » transport.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255                                    1             1 53 28 25 24 1     1 82 51 31 30 1         1 84 84 84 84     1         92   90 86 86 86 86     90 4 4 1     90 2       85 82 82 82 82 82 82   82 3                           1 51     1         100 100 100 72 72       52           1 30     1         63 63 63 27 27 28 27 27 27 27 27         35           1 52 52 52 52     1             2   2           102       102 102             1 28 28 28     1         74 74 74 74 74   74 74         1 1 1 1   1             1 24     1         28 28       28 28   28 337 310 310     27     28 28 28 28 28        
/*
 * Copyright 2014-2016, Sébastien Piquemal <sebpiq@gmail.com>
 *
 * rhizome is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * rhizome 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with rhizome.  If not, see <http://www.gnu.org/licenses/>.
 */
"use strict";
 
var EventEmitter = require('events').EventEmitter
  , dgram = require('dgram')
  , net = require('net')
  , _ = require('underscore')
  , oscMin = require('osc-min')
 
 
exports.createClient = function(host, port, transport) {
  if (transport === 'udp') {
    return new UDPClient(host, port)
  } else if (transport === 'tcp') {
    return new TCPClient(host, port)
  } else throw new Error('invalid transport ' + transport)
}
 
exports.createServer = function(port, transport) {
  if (transport === 'udp') {
    return new UDPServer(port)
  } else if (transport === 'tcp') {
    return new TCPServer(port)
  } else throw new Error('invalid transport ' + transport)
}
 
 
// Base class for OSC over UDP/TCP server
var _BaseServer = exports._BaseServer = function(port) {
  EventEmitter.call(this)
  this.port = port
  this._status = 'stopped'
  this._createSocket()
}
 
_.extend(_BaseServer.prototype, EventEmitter.prototype, {
  // There's no way to know with node 0.10 that a port is already bound with UDP.
  // So to make things a bit more safe (especially for tests), we make sure
  // that we don't bind twice to the same port (otherwise unexpected things might happen).
  start: function(done) {
    if (this._status === 'stopped') {
 
      this._sock.once('listening', () => {
        this._status = 'started'
        this._sock.removeAllListeners('error')
        this._sock.on('error', (err) => this.emit('error', err))
        Eif (done) done()
      })
 
      this._sock.once('error', (err) => {
        this._sock.removeAllListeners('listening')
        if (done) done(err)
        else this.emit('error', err)
      })
      
      this._bindSocket()
    } else Eif (done) done()
  },
 
  stop: function(done) {
    if (this._status === 'started') {
      this._sock.removeAllListeners('close')
      this._sock.once('close', () => {
        this._status = 'stopped'
        this._createSocket()
        this._sock.on('error', () => {})
        done()
      })
      this._sock.close()
    } else done()
  },
 
  // This just creates the socket and adds the event handlers for messaging.
  // At this stage the socket is not bound yet
  // _createSocket: function() { throw new Error('Implement me') },
 
  // This should bind the socket
  // _bindSocket: function() { throw new Error('Implement me') }
 
})
 
 
// OSC over UDP server
var UDPServer = function(port) {
  _BaseServer.apply(this, arguments)
}
 
_.extend(UDPServer.prototype, _BaseServer.prototype, {
 
  transport: 'udp',
 
  _createSocket: function() {
    if (this._sock) this._sock.removeAllListeners()
    this._sock = dgram.createSocket('udp4')
    this._sock.on('message', (msg, rinfo) => {
      msg = oscMin.fromBuffer(msg)
      this.emit('message', msg.address, _.pluck(msg.args, 'value'), rinfo)
    })
  },
 
  _bindSocket: function() { this._sock.bind(this.port) }
 
})
 
 
// OSC over TCP server
var TCPServer = function(port) {
  _BaseServer.apply(this, arguments)
}
 
_.extend(TCPServer.prototype, _BaseServer.prototype, {
 
  transport: 'tcp',
 
  _createSocket: function() {
    if (this._sock) this._sock.removeAllListeners()
    this._sock = net.createServer()
    this._sock.on('connection', (connection) => {
      var buffers = []
      connection.on('error', (err) => this.emit('error', err))
      connection.on('data', (buf) => buffers.push(buf))
      connection.on('end', () => {
        var msg = oscMin.fromBuffer(Buffer.concat(buffers))
        this.emit('message', msg.address, _.pluck(msg.args, 'value'))
        connection.removeAllListeners()
        connection.on('error', () => {})
      })
    })
  },
 
  _bindSocket: function() { this._sock.listen(this.port) }
 
})
 
 
// Base class for OSC over UDP/TCP clients
var _BaseClient = function (host, port) {
  EventEmitter.call(this)
  this.host = host
  this.port = port
  this._ongoingSendsCount = 0
}
 
_.extend(_BaseClient.prototype, EventEmitter.prototype, {
 
  // Sends a message
  // send: function(address, args) { throw new Error('Implement me') }
 
  // Closes client and emits "close"
  close: function() {
    Iif (this._ongoingSendsCount) 
      this._sock.once('_sendsAllDone', () => this.emit('close'))
    else process.nextTick(() => this.emit('close'))
  },
 
  // These 2 callbacks allow to keep track of sending operations,
  // in order to be able to close the client in a clean way.
  _onSendStart: function() {
    this._ongoingSendsCount++
  },
  
  _onSendDone: function() {
    this._ongoingSendsCount--
    if (!this._ongoingSendsCount) this.emit('_sendsAllDone')
  } 
 
})
 
 
// OSC over UDP client
var UDPClient = function (host, port) {
  _BaseClient.apply(this, arguments)
  this._sock = dgram.createSocket('udp4')
  this._sock.on('error', (err) => this.emit('error', err))
}
 
_.extend(UDPClient.prototype, _BaseClient.prototype, {
 
  transport: 'udp',
 
  send: function (address, args) {
    args = args || []
    var buf = oscMin.toBuffer({ address: address, args: args })
    this._onSendStart()
    this._sock.send(buf, 0, buf.length, this.port, this.host, (err, bytesSent) => {
      Iif (bytesSent !== buf.length) 
        err = new Error('was not sent properly')
      if (err) this.emit('error', err)
      this._onSendDone()
    })
  },
 
  close: function() {
    this.on('close', () => {
      this._sock.removeAllListeners('error')
      this._sock.on('error', () => {})
      this._sock = null
    })
    _BaseClient.prototype.close.call(this)
  }
 
})
 
 
// OSC over TCP client
var TCPClient = function (host, port) {
  _BaseClient.apply(this, arguments)
}
 
_.extend(TCPClient.prototype, _BaseClient.prototype, {
 
  transport: 'tcp',
 
  send: function (address, args) {
    args = args || []
    var buf = oscMin.toBuffer({ address: address, args: args })
      , i = -1
      , size = 512
      , sock = net.connect(this.port, this.host)
    sock.on('error', (err) => this.emit('error', err))
    this._onSendStart()
 
    var writeNextPacket = () => {
      if ((size * i) < buf.length) {
        i++
        Eif (sock.write(buf.slice(size * i, size * (i + 1)))) writeNextPacket()
        else sock.once('drain', writeNextPacket)
      } else {
        sock.end()
      }
    }
    sock.on('connect', writeNextPacket)
    sock.on('close', () => {
      sock.removeAllListeners()
      sock.on('error', () => {}) // Silencing potential errors
      this._onSendDone()
    })
  }
 
})