diff --git a/src/bar_modules/bar_module_network.rs b/src/bar_modules/bar_module_network.rs index dab65da..235250d 100644 --- a/src/bar_modules/bar_module_network.rs +++ b/src/bar_modules/bar_module_network.rs @@ -38,18 +38,21 @@ impl bar_modules::BarModuleActions for UnibarModuleNetwork { self.ip_addr_stdout = String::from_utf8(ip_addr_output.stdout).unwrap(); self.ip_addr_stdout.pop(); - self.network_info = serde_json::from_str::(self.ip_addr_stdout.as_str()).unwrap(); - if self.opts.debug_json { - println!("-----> ip_addr - {:#?}", self.network_info); - } - } + let network_data: Value = serde_json::from_str::(self.ip_addr_stdout.as_str()).unwrap(); - // -------------------- - fn get_content(&self) -> String { - if let Some(interfaces) = self.network_info.as_array() { - let up_intf :Vec<_> = interfaces.iter() + if let Some(interfaces) = network_data.as_array() { + if self.opts.debug_json { + println!("-----> network_data - {:#?}", network_data); + } + // Get all interfaces that are up + let mut up_intf :Vec<_> = interfaces.iter() .filter(|el| el["operstate"].as_str().unwrap().contains("UP")) .cloned().collect(); + + // Sort by 'ifname'. This is an unreliable way to proiritize ethernet over wifi. + // Ethenet network interface names normally start with 'e' and wifi interface names + // start with 'w' + up_intf.sort_by(|a, b| a["ifname"].as_str().unwrap().cmp(b["ifname"].as_str().unwrap())); if up_intf.len() > 0 { let inet_addr :Vec<_> = up_intf[0]["addr_info"].as_array().unwrap().iter() .filter(|ai| ai["scope"].as_str().unwrap().contains("global")) @@ -58,24 +61,36 @@ impl bar_modules::BarModuleActions for UnibarModuleNetwork { if self.opts.debug_json { println!("-----> Inet Addr - {:#?}", inet_addr); } - return inet_addr[0]["local"].as_str().unwrap().to_string(); + self.network_info = inet_addr[0].clone(); + self.network_info["ifname"] = up_intf[0]["ifname"].clone(); } } } - return "None".to_string(); + if self.opts.debug_json { + println!("-----> ip_addr - {:#?}", self.network_info); + } + } + + // -------------------- + fn get_content(&self) -> String { + if self.network_info != serde_json::Value::Null { + // If any interface was up, return the local IP address + return self.network_info["local"].as_str().unwrap().to_string(); + } + return "Network down".to_string(); } // -------------------- fn get_icon(&self) -> String { - if let Some(interfaces) = self.network_info.as_array() { - let up_intf :Vec<_> = interfaces.iter() - .filter(|el| el["operstate"].as_str().unwrap().contains("UP")) - .cloned().collect(); - if up_intf.len() > 0 { + if self.network_info != serde_json::Value::Null { + // Select icon based on which interface is up (ethernet or wifi) + if self.network_info["ifname"].as_str().unwrap().to_string().starts_with("w") { return "📶".to_string(); + } else { + return "🌎".to_string(); } } - return "🌎".to_string(); + return "📡".to_string(); } }