Class: EventMachine::MeshRuby

Inherits:
Object
  • Object
show all
Defined in:
lib/meshruby.rb

Overview

Communicates with MeshBlu(tm) via websocket connection.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(uuid, token, url = 'wss://meshblu.octoblu.com:443') ⇒ MeshRuby

Returns a new instance of MeshRuby.



10
11
12
13
# File 'lib/meshruby.rb', line 10

def initialize(uuid, token, url = 'wss://meshblu.octoblu.com:443')
  @uuid, @token, @url, @queue = uuid, token, url, EventMachine::Queue.new
  @socket    = SocketIO::Client::Simple.connect url
end

Instance Attribute Details

#queueObject

Returns the value of attribute queue.



8
9
10
# File 'lib/meshruby.rb', line 8

def queue
  @queue
end

#socketObject

Returns the value of attribute socket.



8
9
10
# File 'lib/meshruby.rb', line 8

def socket
  @socket
end

#tokenObject

Returns the value of attribute token.



8
9
10
# File 'lib/meshruby.rb', line 8

def token
  @token
end

#urlObject

Returns the value of attribute url.



8
9
10
# File 'lib/meshruby.rb', line 8

def url
  @url
end

#uuidObject

Returns the value of attribute uuid.



8
9
10
# File 'lib/meshruby.rb', line 8

def uuid
  @uuid
end

Instance Method Details

#connectObject



15
16
17
18
# File 'lib/meshruby.rb', line 15

def connect
  socket.connect
  create_socket_events
end

#create_socket_eventsObject

Bootstraps all the events for MeshBlu in the correct order.



21
22
23
24
25
26
27
28
29
# File 'lib/meshruby.rb', line 21

def create_socket_events
  #OTHER EVENTS: :identify, :identity, :ready, :disconnect, :message
  this = self
  socket.on :identify do |data|
    auth = {uuid: this.uuid, token: this.token, socketid: data['socketid']}
    emit :identity, auth
  end
  socket.on(:message) { |msg| this.handle_message(msg) }
end

#emit(devices, message_hash) ⇒ Object



39
40
41
# File 'lib/meshruby.rb', line 39

def emit(devices, message_hash)
  socket.emit("message", devices: devices, message: message_hash)
end

#handle_message(message) ⇒ Object

Sanitize messages, making a best effort attempt to hashify them, otherwise returns message as-is.



33
34
35
36
37
# File 'lib/meshruby.rb', line 33

def handle_message(message)
  @queue.push message.is_a?(String) ? JSON.parse(message) : message
rescue JSON::ParserError
  @queue.push message
end

#onmessage(&blk) ⇒ Object



43
44
45
# File 'lib/meshruby.rb', line 43

def onmessage(&blk)
  queue.pop(&blk)
end