import configparser
import logging
import os

from fritzconnection.lib.fritzwlan import FritzWLAN

logger = logging.getLogger(__name__)


class FritzWLANStatus(object):

	def __init__(self, connection, prefs):
		fname = os.path.join(os.path.dirname(__file__), 'fritzBackwardSearch.ini')
		if os.path.isfile(fname):
			self.wlan_prefs = self.__read_wlan_configuration__(fname)
		else:
			logger.error('{} not found'.format(fname))
			exit(1)

		self.prefs = prefs
		self.connection = connection

	def __read_wlan_configuration__(self, filename):
		cfg = configparser.ConfigParser(default_section=None)
		cfg.read(filename)
		wlan = {}
		for name, value in cfg.items('WLAN'):
			wlan[name] = value.replace('-', ':')
		return wlan

	def get_active_devices(self):
		online_status = {}
		hosts = [host['mac']
				 for host in FritzWLAN(self.connection, service=1).get_hosts_info() if host['status'] == True]  # 2.4GHz
		hosts += [host['mac']
				  for host in FritzWLAN(self.connection, service=2).get_hosts_info() if host['status'] == True]  # 5GHz
		hosts += [host['mac']
				  for host in FritzWLAN(self.connection, service=3).get_hosts_info() if host['status'] == True]  # GuestAccount
		for name, mac in self.wlan_prefs.items():
			online_status[name] = 1 if mac in hosts else 0
		# send as mqtt message
		cmd = 'mosquitto_pub -d -h homematic-raspi -t server/fritz/maconline/'
		for name, status in online_status.items():
			os.system("{}{} -m {}".format(cmd, name, status))

@@ -784,16 +784,25 @@
 self):%0D%0A
+%09%09try:%0D%0A%09
 %09%09online
@@ -813,24 +813,25 @@
 tus = %7B%7D%0D%0A%09%09
+%09
 hosts = %5Bhos
@@ -844,17 +844,17 @@
 '%5D%0D%0A%09%09%09%09
- 
+%09
 for host
@@ -948,24 +948,25 @@
 # 2.4GHz%0D%0A%09%09
+%09
 hosts += %5Bho
@@ -972,34 +972,33 @@
 ost%5B'mac'%5D%0D%0A%09%09%09%09
+%09
-  
 for host in Frit
@@ -1086,16 +1086,17 @@
 5GHz%0D%0A%09%09
+%09
 hosts +=
@@ -1114,18 +1114,17 @@
 '%5D%0D%0A%09%09%09%09
-  
+%09
 for host
@@ -1224,24 +1224,25 @@
 tAccount%0D%0A%09%09
+%09
 for name, ma
@@ -1268,24 +1268,25 @@
 s.items():%0D%0A
+%09
 %09%09%09online_st
@@ -1324,16 +1324,17 @@
 else 0%0D%0A
+%09
 %09%09# send
@@ -1351,16 +1351,48 @@
 essage%0D%0A
+%09%09%09logger.info(online_status)%0D%0A%09
 %09%09cmd = 
@@ -1455,24 +1455,25 @@
 online/'%0D%0A%09%09
+%09
 for name, st
@@ -1504,16 +1504,17 @@
 ems():%0D%0A
+%09
 %09%09%09os.sy
@@ -1555,12 +1555,97 @@
 , status))%0D%0A
+%09%09except Exception as e:%0D%0A%09%09%09logger.error(%22Cannot post MQTT request: %7B%7D%22.format(e))%0D%0A

add try/except block