Skip to content

Instantly share code, notes, and snippets.

@njh
Created April 14, 2012 14:09
Show Gist options
  • Save njh/2384664 to your computer and use it in GitHub Desktop.
Save njh/2384664 to your computer and use it in GitHub Desktop.
Subscribe to MQTT messages in browser using HTML5 Server-Sent Events
#!/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>
@andypiper
Copy link

Also fails if I try binding to a broker on localhost. Same MQTT connection exception.

@njh
Copy link
Author

njh commented Apr 15, 2012

Yup, it certainly should work. I am using ruby 1.8.7 on Mac OS X.

The error message you are seeing isn't the real problem. I have explained a bit of the background in the ticket you raised:
http://github.com/njh/ruby-em-mqtt/issues/1

While I was playing with it yesterday, debugging a problem, I commented out the two halves of the code, one at a time.

Commenting out:

WebApp.run!

will disable the Sinatra web server, making it easier to debug the MQTT code.

Commenting out:

MyConnection.connect('test.mosquitto.org') do |c|
    c.subscribe('#')
    c.connections = WebApp.connections
end

Disables the MQTT, making it easier to find bugs in the Sinatra code.

@njh
Copy link
Author

njh commented Apr 15, 2012

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment