Class: MagicMirror::Mirror

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

Instance Method Summary collapse

Constructor Details

#initializeMirror

Returns a new instance of Mirror.



4
5
6
# File 'lib/magic_mirror/mirror.rb', line 4

def initialize

end

Instance Method Details

#command_cacheObject



55
56
57
# File 'lib/magic_mirror/mirror.rb', line 55

def command_cache
  MagicMirror.command_cache
end

#command_cache=(value) ⇒ Object



59
60
61
# File 'lib/magic_mirror/mirror.rb', line 59

def command_cache=(value)
  MagicMirror.command_cache = value
end

#init_servers!Object



8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/magic_mirror/mirror.rb', line 8

def init_servers!
  Thin::Logging.silent = true
  print "\nActivating the Magic Mirror."

  @threads = []

  # start sinatra
  @threads << start_sinatra
  @threads << start_faye

  puts "\nThe Magic Mirror is Activated.  Navigate to http://127.0.0.1:4567"
  self
end

#speak_into(msg) ⇒ Object

sends messages through faye server to web interface



64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/magic_mirror/mirror.rb', line 64

def speak_into(msg)
  require 'net/http'
  channel = "/0001"

  message = {:channel => channel, :data => msg}
  uri = URI.parse("http://localhost:#{FAYE_PORT}/faye")
  begin
    Net::HTTP.post_form(uri, :message => message.to_json)
  rescue
    $stderr.puts "failed to send message to faye server and thus webclient"
    return false
  end
  true
end

#start_fayeObject



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/magic_mirror/mirror.rb', line 39

def start_faye
  queue = Queue.new # allows waiting for sinatra boot

  Thread.new {
    bayeux = Faye::RackAdapter.new(:mount => '/faye', :timeout => 25)
    bayeux.listen(FAYE_PORT)
    bayeux.run!
    #run bayeux
  }

  #queue.pop # blocks until server is booted
  wait_until_faye_is_up
  print "."

end

#start_sinatraObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/magic_mirror/mirror.rb', line 22

def start_sinatra
  queue = Queue.new # allows waiting for sinatra boot
  $stderr_backup = $stderr.dup
  $stderr.reopen("/dev/null", "w")

  Thread.new {
    SinatraSilver::App.run! do |server|
      queue.push("started") # tells caller thread to continue
    end
  }

  queue.pop # blocks until sinatra is booted
  print "."

  $stderr = $stderr_backup.dup
end

#wait_until_faye_is_upObject



79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/magic_mirror/mirror.rb', line 79

def wait_until_faye_is_up
  require 'net/http'
  while(true) do
    begin
      message = {:channel => "/0001", :data => "booted"}
      uri = URI.parse("http://localhost:#{FAYE_PORT}/faye")
      response = Net::HTTP.post_form(uri, :message => message.to_json)
    rescue
    end

    break if response and response.code == "200" and response.body == "[{\"channel\":\"/0001\",\"successful\":true}]"
    sleep 0.1
  end
end