Module: OSC::Packet

Defined in:
lib/osc.rb

Overview

Unit of transmission. Really needs revamping

Class Method Summary collapse

Class Method Details

.decode(packet) ⇒ Object

Takes a string containing one packet



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/osc.rb', line 242

def self.decode(packet)
  # XXX I think it would have been better to use a StringScanner. Maybe I
  # will convert it someday...
  io = StringIO.new(packet)
  id = decode_string(io)
  if id == '#bundle'
    b = Bundle.new(decode_timetag(io))
    until io.eof?
      l = io.read(4).unpack('N')[0]
      s = io.read(l)
      b << decode(s)
    end
    b
  elsif id =~ /^\//
	m = Message.new(id)
	if io.getc == ?,
	  tags = decode_string(io)
	  tags.scan(/./) do |t|
 case t
 when 'i'
   m << decode_int32(io)
 when 'f'
   m << decode_float32(io)
 when 's'
   m << decode_string(io)
 when 'b'
   m << decode_blob(io)

 # right now we skip over nonstandard datatypes, but we'll want to
 # add these datatypes too.
 when /[htd]/; io.read(8)
 when 'S'; decode_string(io)
 when /[crm]/; io.read(4)
 when /[TFNI\[\]]/;
 end
	  end
	end
	m
  end
end

.encode(o) ⇒ Object



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/osc.rb', line 298

def self.encode(o)
  case o
  when Fixnum;  [o].pack 'N'
  when Float;   [o].pack 'g'
  when Blob;    pad([o.size].pack('N') + o)
  when String;  pad(o.sub(/\000.*\Z/, '') + "\000")
  when TimeTag; o.to_a.pack('NN')

  when Message
	s = encode(o.address)
	s << encode(','+o.types)
	s << o.args.collect{|x| encode(x)}.join

  when Bundle
	s = encode('#bundle')
	s << encode(o.timetag)
	s << o.args.collect { |x| 
	  x2 = encode(x); [x2.size].pack('N') + x2 
	}.join
  end
end

.pad(s) ⇒ Object



283
284
285
# File 'lib/osc.rb', line 283

def self.pad(s)
  s + ("\000" * ((4 - s.size)%4))
end

.tag(o) ⇒ Object



287
288
289
290
291
292
293
294
295
296
# File 'lib/osc.rb', line 287

def self.tag(o)
  case o
  when Fixnum;  'i'
  when TimeTag; 't'
  when Float;   'f'
  when Blob;    'b'
  when String;  's'
  else;         nil
  end
end