Detecting bluetooth devices with hcitool scan
1 2 #!/usr/bin/ruby 3 4 #file: bt_scan.rb 5 6 require 'rexml/document' 7 include REXML 8 9 while true 10 filein = File.new('bt_found.xml','r') 11 doc = Document.new(filein) 12 filein.close 13 14 fileout = File.new('bt_found.xml','w') 15 16 result = `hcitool scan` 17 found = result.split(/\n/) # retrieve each found device 18 found.delete_at(0) # remove the item containing 'scanning ...' 19 20 found.each do |b| 21 node_found = Element.new('found') 22 p = b.split(/\t/) # retrieve device details 23 id = p[1] 24 name = p[2] 25 puts "name #{name} --- id #{id}" 26 node_id = Element.new('id') 27 node_name = Element.new('name') 28 node_date = Element.new('date') 29 30 node_id.text = id 31 node_name.text = name 32 node_date.text = Time.now 33 34 node_found << node_id 35 node_found << node_name 36 node_found << node_date 37 doc.root << node_found 38 end 39 40 41 fileout.puts doc 42 fileout.close 43 puts 'sleeping' 44 sleep 10 # during this time we can kill the script, 45 # otherwise we risk losing the contents of the xml file. 46 puts 'awake' 47 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.