Skip to content

Instantly share code, notes, and snippets.

@mostlyobvious
Created September 18, 2011 14:08
Show Gist options
  • Save mostlyobvious/1225106 to your computer and use it in GitHub Desktop.
Save mostlyobvious/1225106 to your computer and use it in GitHub Desktop.
require 'dbus'
require 'eventmachine'
module EM
module Avahi
AVAHI = "org.freedesktop.Avahi"
AVAHI_SERVER = "org.freedesktop.Avahi.Server"
AVAHI_BROWSER = "org.freedesktop.Avahi.ServiceBrowser"
class ServiceBrowser
def initialize
@bus = DBus::SystemBus.instance
@server = @bus.introspect(AVAHI, '/')[AVAHI_SERVER]
@connection = EM.watch(@bus.socket, DBusHandler) do |handler|
handler.bus = @bus
end
@connection.notify_readable = true
end
def browse(service, &blk)
browser = @server.ServiceBrowserNew(-1, -1, service, "", 0)
matcher = DBus::MatchRule.new.tap do |mr|
mr.type = "signal"
mr.interface = AVAHI_BROWSER
mr.path = browser.first
end
@bus.add_match(matcher) do |msg, _|
blk.call(msg)
end
end
end
module DBusHandler
attr_accessor :bus
def notify_readable
bus.update_buffer
while msg = bus.pop_message
bus.process(msg)
end
end
end
end
end
EM.run do
trap("INT") { EM.stop }
avahi = EM::Avahi::ServiceBrowser.new
avahi.browse('_presence._tcp') do |msg|
puts msg.inspect
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment