Skip to content

Instantly share code, notes, and snippets.

@ross-nordstrom
Last active August 29, 2015 14:27
Show Gist options
  • Save ross-nordstrom/14b43059f6cf10461595 to your computer and use it in GitHub Desktop.
Save ross-nordstrom/14b43059f6cf10461595 to your computer and use it in GitHub Desktop.
Get a breakdown of 2.4GHz channel utilization. Assumes wireless interface accessible at "wlan0".
#!/usr/bin/env ruby
require 'json'
ALLOWED_CHANNELS = ['Ch 1', 'Ch 6', 'Ch 11']
Infinity = Float::INFINITY
wifi = `iwlist wlan0 scan`
pieces2ghz = wifi.split("Cell ")[1..-1].select{|x| x.include?('Frequency:2') && x.include?('Channel ') }
data = pieces2ghz.map{ |x| [ x.split('Channel ')[1].split(')')[0].to_i, (x.split('Signal level=')[1].split('/')[0] rescue '0').to_i, (x.split('Protocol:')[1].split("\n")[0] rescue '[UNKNOWN]') ] }
channels = {}
channels = data.reduce(channels) do |channels, x|
k = "Ch #{x[0]}"
channels[k] = [channels[k] || -100, x[1] || -100].max
channels
end
if channels.empty?
puts "Unable to get Wi-Fi information. Is Wi-Fi on?"
exit 1
end
interferers = channels.keys - ALLOWED_CHANNELS
if !interferers.empty?
interference = interferers.reduce(-Infinity) { |max, ch| [channels[ch].to_f, max.to_f].max }
end
channels[:interference] = (interference == -Infinity) ? null : interference.to_i
# Some scans produce negative dBMs (correct), but some (raspi) produce positive (wrong)
if channels.first[1] > 0
channels[:interference_state] = interference > 40 ? 3 : (interference > 0 ? 2 : 1 )
else
channels[:interference_state] = interference > -60 ? 3 : (interference > -100 ? 2 : 1 )
end
puts channels.to_json.gsub(/"/, "'")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment