Created
April 14, 2012 14:09
-
-
Save njh/2384664 to your computer and use it in GitHub Desktop.
Subscribe to MQTT messages in browser using HTML5 Server-Sent Events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'rubygems' | |
require 'eventmachine' | |
require 'em-mqtt' | |
require 'sinatra/base' | |
require 'thin' | |
class WebApp < Sinatra::Base | |
set :server => 'thin' | |
enable :inline_templates | |
def self.connections | |
@connections ||= [] | |
end | |
get '/' do | |
erb :index | |
end | |
get '/stream' do | |
content_type 'text/event-stream' | |
stream :keep_open do |out| | |
WebApp.connections << out | |
out.callback { WebApp.connections.delete(out) } | |
end | |
end | |
end | |
class MyConnection < EventMachine::MQTT::ClientConnection | |
attr_accessor :connections | |
def receive_msg(packet) | |
connections.each do |c| | |
c << "data: #{packet.topic}: #{packet.payload}\n\n"; | |
end | |
end | |
end | |
EventMachine.run do | |
MyConnection.connect('test.mosquitto.org') do |c| | |
c.subscribe('#') | |
c.connections = WebApp.connections | |
end | |
WebApp.run! | |
end | |
__END__ | |
@@ layout | |
<html> | |
<head> | |
<title>MQTT EventSource</title> | |
<meta charset="utf-8" /> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> | |
</head> | |
<body><%= yield %></body> | |
</html> | |
@@ index | |
<pre id='messages'></pre> | |
<script> | |
var es = new EventSource('/stream'); | |
es.onmessage = function(e) { | |
$('#messages').append(e.data + "\n"); | |
$('html, body').scrollTop($(document).height()); | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
At one point I was going to make the main mqtt gem powered by EventMachine, but I have had such trouble with debugging it, that I thought it was a bad idea.
Love EventMachine and the ideas behind it, but it can be a real pain.