created on 13 Jul 2008, by Syndication, read more…
A trivial Ruby script to store the bluetooth devices found with the shell command 'hcitool scan'.
#!/usr/bin/ruby
#file: bt_scan.rb
require 'rexml/document'
include REXML
while true
filein = File.new('bt_found.xml','r')
doc = Document.new(filein)
filein.close
fileout = File.new('bt_found.xml','w')
result = `hcitool scan`
found = result.split(/\n/) # retrieve each found device
found.delete_at(0) # remove the item containing 'scanning ...'
found.each do |b|
node_found = Element.new('found')
p = b.split(/\t/) # retrieve device details
id = p[1]
name = p[2]
puts "name #{name} --- id #{id}"
node_id = Element.new('id')
node_name = Element.new('name')
node_date = Element.new('date')
node_id.text = id
node_name.text = name
node_date.text = Time.now
node_found node_found node_found doc.root end
fileout.puts doc
fileout.close
puts 'sleeping'
sleep 10 # during this time we can kill the script,
# otherwise we risk losing the contents of the xml file.
puts 'awake'
end
Note: Shell commands don't really have much to do with Ruby, however if there is no easy to use bluetooth libraries then I will of course use what's available.