class EventMachine::MeshRuby

Communicates with MeshBlu(tm) via websocket connection.

Attributes

queue[RW]
socket[RW]
token[RW]
url[RW]
uuid[RW]

Public Class Methods

new(uuid, token, url = 'wss://meshblu.octoblu.com:443') click to toggle source
# 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::Client.new url
end

Public Instance Methods

connect() click to toggle source
# File lib/meshruby.rb, line 15
def connect
  socket.connect
  create_socket_events
  self
end
create_socket_events() click to toggle source

Bootstraps all the events for MeshBlu in the correct order.

# File lib/meshruby.rb, line 22
def create_socket_events
  #OTHER EVENTS: :identify, :identity, :ready, :disconnect, :message
  this = self; socket = this.socket # socket.io-client bugs?
  socket.on :connect do
    socket.on :identify do |data|
      auth = {uuid: this.uuid, token: this.token}
      emit :identity, auth
    end
    socket.on(:message) { |msg| this.push(msg); this.pop }
  end
end
credentials() click to toggle source
# File lib/meshruby.rb, line 51
def credentials
  @credentials ||= {uuid: @uuid, token: @token}
end
data(telemetry) click to toggle source
# File lib/meshruby.rb, line 55
def data(telemetry)
  case telemetry
  when Hash then nil # do stuff
  else telemetry = {data: telemetry}
  end
  socket.emit("data", telemetry.merge!(credentials))
end
emit(devices, message_hash) click to toggle source

TODO: Rename to 'message', since this is not the only thing we're emitting

# File lib/meshruby.rb, line 47
def emit(devices, message_hash)
  socket.emit("message", message_hash.merge(devices: devices))
end
onmessage(&blk) click to toggle source
# File lib/meshruby.rb, line 63
def onmessage(&blk)
  @onmessage = blk
end
pop() click to toggle source
# File lib/meshruby.rb, line 42
def pop
  @queue.pop(&@onmessage) if @onmessage
end
push(message) click to toggle source

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

# File lib/meshruby.rb, line 36
def push(message)
  @queue.push message.is_a?(String) ? JSON.parse(message) : message
rescue JSON::ParserError
  @queue.push message
end
toggle_debug!() click to toggle source
# File lib/meshruby.rb, line 67
def toggle_debug!
  if @debugger
    socket.remove_listener(@debugger)
  else
    @debugger = socket.on(:*) { |a, b| puts "#{a} #{b}" }
  end
end