From 8d4856db56a6d7b1cc13e865c489f745579628b7 Mon Sep 17 00:00:00 2001 From: Martin Weinelt Date: Wed, 25 Mar 2015 14:11:00 +0100 Subject: [PATCH] lib/batman: refactor gateway handling --- lib/batman.py | 38 ++++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/lib/batman.py b/lib/batman.py index a4aeca2..4f6b943 100644 --- a/lib/batman.py +++ b/lib/batman.py @@ -12,6 +12,9 @@ class Batman(object): self.mesh_interface = mesh_interface self.alfred_sock = alfred_sockpath + # compile regular expressions only once on startup + self.mac_addr_pattern = re.compile(r'(([a-z0-9]{2}:){5}[a-z0-9]{2})') + def vis_data(self, batadv_vis=False): vds = self.vis_data_batctl_legacy() if batadv_vis: @@ -60,36 +63,35 @@ class Batman(object): output = subprocess.check_output( ['batctl', '-m', self.mesh_interface, 'gwl', '-n']) output_utf8 = output.decode('utf-8') - lines = output_utf8.splitlines() - - own_mac = re.match(r"^.*MainIF/MAC: [^/]+/([0-9a-f:]+).*$", - lines[0]).group(1) + rows = output_utf8.splitlines() gateways = [] - gw_mode = self.gateway_mode() - if gw_mode['mode'] == 'server': - gateways.append(own_mac) - for line in lines: - gw_line = re.match(r"^(?:=>)? +([0-9a-f:]+) ", line) - if gw_line: - gateways.append(gw_line.group(1)) + # local gateway + header = rows.pop(0) + mode, bandwidth = self.gateway_mode() + if mode == 'server': + local_gw_mac = self.mac_addr_pattern.search(header).group(0) + gateways.append(local_gw_mac) + + # remote gateway(s) + for row in rows: + match = self.mac_addr_pattern.search(row) + if match: + gateways.append(match.group(1)) return gateways def gateway_mode(self): """ Parse "batctl -m gw" + return: tuple mode, bandwidth, if mode != server then bandwidth is None """ output = subprocess.check_output( ['batctl', '-m', self.mesh_interface, 'gw']) - elements = output.decode("utf-8").split() - mode = elements[0] - if mode == 'server': - return {'mode': 'server', - 'bandwidth': elements[3]} - else: - return {'mode': mode} + chunks = output.decode("utf-8").split() + + return chunks[0], chunks[3] if 3 in chunks else None if __name__ == "__main__": bc = Batman()