[WirelessLanSetup] fix bug and AP scan menu
[vuplus_dvbapp] / lib / python / Plugins / SystemPlugins / WirelessLanSetup / plugin.py
index 3681a9f..1331a69 100755 (executable)
@@ -5,7 +5,6 @@ from Screens.Standby import *
 from Screens.VirtualKeyBoard import VirtualKeyBoard
 from Screens.HelpMenu import HelpableScreen
 from Components.Network import iNetwork
-#from Screens.NetworkSetup import NameserverSetup, NetworkAdapterTest
 from Screens.NetworkSetup import NameserverSetup
 from Components.Sources.StaticText import StaticText
 from Components.Sources.Boolean import Boolean
@@ -24,75 +23,168 @@ from Tools.Directories import resolveFilename, SCOPE_PLUGINS, SCOPE_CURRENT_SKIN
 from Tools.LoadPixmap import LoadPixmap
 from Plugins.Plugin import PluginDescriptor
 from enigma import eTimer, ePoint, eSize, RT_HALIGN_LEFT, eListboxPythonMultiContent, gFont
-from os import path as os_path, system as os_system, unlink
+from os import path as os_path, system as os_system, unlink, listdir, access, R_OK, popen
 from re import compile as re_compile, search as re_search
 from Tools.Directories import fileExists
 import time
+from pythonwifi.iwlibs import Wireless
+from pythonwifi import flags as wifi_flags
 
-class WlanSelection(Screen):
-       skin = """
-       <screen name="WlanSelection" position="209,48" size="865,623" title="Wireless Network Selection..." flags="wfNoBorder" backgroundColor="transparent">   
-               <ePixmap pixmap="Vu_HD/Bg_EPG_view.png" zPosition="-1" position="0,0" size="865,623" alphatest="on" />
-               <ePixmap pixmap="Vu_HD/menu/ico_title_Setup.png" position="32,41" size="40,40" alphatest="blend"  transparent="1" />
-               <eLabel text="Wireless Network Selection..." position="90,50" size="600,32" font="Semiboldit;32" foregroundColor="#5d5d5d" backgroundColor="#27b5b9bd" transparent="1" />
-               <ePixmap pixmap="Vu_HD/icons/clock.png" position="750,55" zPosition="1" size="20,20" alphatest="blend" />
-               <widget source="global.CurrentTime" render="Label" position="770,57" zPosition="1" size="50,20" font="Regular;20" foregroundColor="#1c1c1c" backgroundColor="#27d9dee2" halign="right" transparent="1">
-                       <convert type="ClockToText">Format:%H:%M</convert>
-               </widget>
-               <ePixmap pixmap="Vu_HD/buttons/red.png" position="45,98" size="25,25" alphatest="blend" />
-               <widget source="key_red" render="Label" position="66,97" zPosition="1" size="150,25" font="Regular;20" halign="center" valign="center" backgroundColor="darkgrey" foregroundColor="#1c1c1c" transparent="1" />
-               <ePixmap pixmap="Vu_HD/border_menu.png" position="120,140" zPosition="-1" size="342,358" transparent="1" alphatest="blend" />
-               <widget name="menulist" position="130,150" size="322,338" transparent="1" backgroundColor="#27d9dee2" zPosition="10" scrollbarMode="showOnDemand" />
-       </screen>"""
-       
+class WlanSelection(Screen,HelpableScreen):
+       skin =  """
+               <screen position="center,center" size="510,400" title="Wireless Network Adapter Selection..." >
+                       <ePixmap pixmap="skin_default/div-h.png" position="0,350" zPosition="1" size="560,2" />
+                       <ePixmap pixmap="skin_default/border_menu.png" position="10,10" zPosition="1" size="250,300" transparent="1" alphatest="on" />
+
+                       <ePixmap pixmap="skin_default/buttons/red.png" position="10,360" size="140,40" alphatest="on" />
+                       <ePixmap pixmap="skin_default/buttons/green.png" position="360,360" size="140,40" alphatest="on" />
+
+                       <widget source="key_red" render="Label" position="10,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
+                       <widget source="key_green" render="Label" position="360,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />
+
+                       <widget name="menulist" position="20,20" size="230,260" transparent="1" backgroundColor="#371e1c1a" zPosition="10" scrollbarMode="showOnDemand" />
+                       <widget source="description" render="Label" position="305,10" size="195,300" font="Regular;19" halign="center" valign="center" />
+               </screen>
+               """
        def __init__(self, session):
                Screen.__init__(self,session)
+               HelpableScreen.__init__(self)
                self.mainmenu = self.getWlandevice()
                self["menulist"] = MenuList(self.mainmenu)
-               self["key_red"] = StaticText(_("Close"))                
-               self["OkCancelActions"] = ActionMap(["ShortcutActions", "SetupActions" ],
+               self["key_red"] = StaticText(_("Close"))
+               self["key_green"] = StaticText(_("Select"))
+               self["description"] = StaticText()
+               self["description"].setText(_("Select Wireless Lan module. \n" ))
+               self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
                {
-                       "ok": self.ok,
-                       "cancel": self.close,
-                       "red": self.close,
-               }, -2)
+                       "ok": (self.ok, _("select interface")),
+                       "cancel": (self.close, _("exit network interface list")),
+               })
 
-       def ok(self):
-               ifaces=self["menulist"].getCurrent()[1]
-               if ifaces == None:
-                       pass
-               else:
-                       self.session.open(WlanSetup,ifaces)
+               self["ColorActions"] = HelpableActionMap(self, "ColorActions",
+               {
+                       "green": (self.ok, _("select interface")),
+                       "red": (self.close, _("exit network interface list")),
+               })
+               self.updateInterfaces()
+               self.onClose.append(self.cleanup)
 
+       def updateInterfaces(self):
+               iNetwork.config_ready = False
+               iNetwork.msgPlugins()
+               iNetwork.getInterfaces()
+
+       def checkIfaceMode(self, iface = None):
+               try:
+                       obj = Wireless(iface)
+                       if obj.getMode() == 'Master':
+                               return -1
+                       else:
+                               return 0
+               except:
+                       return -2
+
+       def ok(self):
+#              print len(self["menulist"].list)
+               if len(self["menulist"].list) == 0:
+                       self.session.open(MessageBox, (_("Can not find any WirelessLan Module\n")),MessageBox.TYPE_ERROR,5 )
+                       return
+               iface=self["menulist"].getCurrent()[1]
+               if iface == None:
+                       return
+               elif iNetwork.getAdapterAttribute(iface, "up") == True:
+                       ret = self.checkIfaceMode(iface)
+                       if ret == -2:
+                               self.session.open(MessageBox, (_("Invalid WirelessLan Module.\n")),MessageBox.TYPE_ERROR,5 )
+                               return
+                       elif ret == -1:
+                               self.session.open(MessageBox, (_("Can not setup WirelessLan Module in 'AP Mode'\n")),MessageBox.TYPE_ERROR,5 )
+                               return
+               self.session.open(WlanSetup, iface)
 
        def getWlandevice(self):
                list = []
-               for x in iNetwork.getAdapterList():
-                       if x.startswith('eth'):
+               for x in iNetwork.getInstalledAdapters():
+                       if x.startswith('eth') or x.startswith('br') or x.startswith('mon'):
                                continue
-                       list.append((iNetwork.getFriendlyAdapterName(x),x))
+                       description=self.getAdapterDescription(x)
+                       if description == "Unknown network adapter":
+                               list.append((description,x))
+                       else:
+                               list.append((description + " (%s)"%x,x))
                return list
-#              self.adapters = [(iNetwork.getFriendlyAdapterName(x),x) for x in iNetwork.getAdapterList()]
-#              print self.adapters
-#              return self.adapters
-               
 
+       def getAdapterDescription(self, iface):
+               classdir = "/sys/class/net/" + iface + "/device/"
+               driverdir = "/sys/class/net/" + iface + "/device/driver/"
+               if os_path.exists(classdir):
+                       files = listdir(classdir)
+                       if 'driver' in files:
+                               if os_path.realpath(driverdir).endswith('rtw_usb_drv'):
+                                       return _("Realtek")+ " " + _("WLAN adapter.")
+                               elif os_path.realpath(driverdir).endswith('ath_pci'):
+                                       return _("Atheros")+ " " + _("WLAN adapter.")
+                               elif os_path.realpath(driverdir).endswith('zd1211b'):
+                                       return _("Zydas")+ " " + _("WLAN adapter.")
+                               elif os_path.realpath(driverdir).endswith('rt73'):
+                                       return _("Ralink")+ " " + _("WLAN adapter.")
+                               elif os_path.realpath(driverdir).endswith('rt73usb'):
+                                       return _("Ralink")+ " " + _("WLAN adapter.")
+                               elif self.isRalinkModule(iface):
+                                       return _("Ralink")+ " " + _("WLAN adapter.")
+                               else:
+                                       return str(os_path.basename(os_path.realpath(driverdir))) + " " + _("WLAN adapter")
+                       else:
+                               return _("Unknown network adapter")
+               else:
+                       return _("Unknown network adapter")
+
+       def isRalinkModule(self, iface):
+# check vendor ID for lagacy driver
+               vendorID = "148f" # ralink vendor ID
+               idVendorPath = "/sys/class/net/%s/device/idVendor" % iface
+               if access(idVendorPath, R_OK):
+                       fd = open(idVendorPath, "r")
+                       data = fd.read().strip()
+                       fd.close()
+
+#                      print "Vendor ID : %s" % data
+
+                       if data == vendorID:
+                               return True
+
+# check sys driver path for kernel driver
+               ralinkKmod = "rt2800usb" # ralink kernel driver name
+               driverPath = "/sys/class/net/%s/device/driver/" % iface
+               if os_path.exists(driverPath):
+                       driverName = os_path.basename(os_path.realpath(driverPath))
+
+#                      print "driverName : %s" % driverName
+
+                       if driverName == ralinkKmod:
+                               return True
+
+               return False
+
+       def cleanup(self):
+               iNetwork.stopGetInterfacesConsole()
 
 class WlanSetup(Screen,HelpableScreen):
-       skin = """
-       <screen name="WlanSetup" position="209,48" size="865,623" title="Wireless Network Configuration..." flags="wfNoBorder" backgroundColor="transparent">   
-               <ePixmap pixmap="Vu_HD/Bg_EPG_view.png" zPosition="-1" position="0,0" size="865,623" alphatest="on" />
-               <ePixmap pixmap="Vu_HD/menu/ico_title_Setup.png" position="32,41" size="40,40" alphatest="blend"  transparent="1" />
-               <eLabel text="Wireless Network Configuration..." position="90,50" size="600,32" font="Semiboldit;32" foregroundColor="#5d5d5d" backgroundColor="#27b5b9bd" transparent="1" />
-               <ePixmap pixmap="Vu_HD/icons/clock.png" position="750,55" zPosition="1" size="20,20" alphatest="blend" />
-               <widget source="global.CurrentTime" render="Label" position="770,57" zPosition="1" size="50,20" font="Regular;20" foregroundColor="#1c1c1c" backgroundColor="#27d9dee2" halign="right" transparent="1">
-                       <convert type="ClockToText">Format:%H:%M</convert>
-               </widget>
-               <ePixmap pixmap="Vu_HD/buttons/red.png" position="45,98" size="25,25" alphatest="blend" />
-               <widget source="key_red" render="Label" position="66,97" zPosition="1" size="150,25" font="Regular;20" halign="center" valign="center" backgroundColor="darkgrey" foregroundColor="#1c1c1c" transparent="1" />
-               <ePixmap pixmap="Vu_HD/border_menu.png" position="120,140" zPosition="-1" size="342,358" transparent="1" alphatest="blend" />
-               <widget name="menulist" position="130,150" size="322,338" transparent="1" backgroundColor="#27d9dee2" zPosition="10" scrollbarMode="showOnDemand" />
-       </screen>"""
+       skin =  """
+               <screen position="center,center" size="510,400" title="Wireless Network Setup Menu..." >
+                       <ePixmap pixmap="skin_default/div-h.png" position="0,350" zPosition="1" size="560,2" />
+                       <ePixmap pixmap="skin_default/border_menu.png" position="10,10" zPosition="1" size="250,300" transparent="1" alphatest="on" />
+
+                       <ePixmap pixmap="skin_default/buttons/red.png" position="10,360" size="140,40" alphatest="on" />
+                       <ePixmap pixmap="skin_default/buttons/green.png" position="360,360" size="140,40" alphatest="on" />
+
+                       <widget source="key_red" render="Label" position="10,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
+                       <widget source="key_green" render="Label" position="360,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />
+
+                       <widget name="menulist" position="20,20" size="230,260" transparent="1" backgroundColor="#371e1c1a" zPosition="10" scrollbarMode="showOnDemand" />
+                       <widget source="description" render="Label" position="305,10" size="195,300" font="Regular;19" halign="center" valign="center" />
+               </screen>
+               """
        def __init__(self, session, ifaces):
                Screen.__init__(self, session)
                HelpableScreen.__init__(self)
@@ -103,16 +195,13 @@ class WlanSetup(Screen,HelpableScreen):
                self.mainmenu = self.MakeMenu()
                self["menulist"] = MenuList(self.mainmenu)
                self["key_red"] = StaticText(_("Close"))
+               self["key_green"] = StaticText(_("Select"))
                self["description"] = StaticText()
                self["IFtext"] = StaticText()
                self["IF"] = StaticText()
-               self["Statustext"] = StaticText()
-               self["statuspic"] = MultiPixmap()
-               self["statuspic"].hide()
+               self.onLayoutFinish.append(self.loadDescription)
                
                self.oktext = _("Press OK on your remote control to continue.")
-               self.reboottext = _("Your STB will restart after pressing OK on your remote control.")
-               self.errortext = _("No working wireless network interface found.\n Please verify that you have attached a compatible WLAN device or enable your local network interface.")      
                
                self["WizardActions"] = HelpableActionMap(self, "WizardActions",
                        {
@@ -130,7 +219,8 @@ class WlanSetup(Screen,HelpableScreen):
 
                self["ColorActions"] = HelpableActionMap(self, "ColorActions",
                        {
-                       "red": (self.close, _("exit networkadapter setup menu")),       
+                       "red": (self.close, _("exit networkadapter setup menu")),
+                       "green": (self.ok, _("select menu entry")),
                        })
 
                self["actions"] = NumberActionMap(["WizardActions","ShortcutActions"],
@@ -143,19 +233,44 @@ class WlanSetup(Screen,HelpableScreen):
                        "left": self.left,
                        "right": self.right,
                }, -2)
+               self.onClose.append(self.cleanup)
+
+       def loadDescription(self):
+               if self["menulist"].getCurrent()[1] == 'setting':
+                       self["description"].setText(_("Edit the network configuration of your STB.\n" ) + self.oktext )
+               if self["menulist"].getCurrent()[1] == 'scanap':
+                       self["description"].setText(_("Scan your network for wireless access points and connect to them using your selected wireless device.\n" ) + self.oktext )
+               if self["menulist"].getCurrent()[1] == 'dns':
+                       self["description"].setText(_("Edit the Nameserver configuration of your STB.\n" ) + self.oktext )
+               if self["menulist"].getCurrent()[1] == 'status':
+                       self["description"].setText(_("Shows the state of your wireless LAN connection.\n" ) + self.oktext )
+               if self["menulist"].getCurrent()[1] == 'test':
+                       self["description"].setText(_("Test the network configuration of your STB.\n" ) + self.oktext )
+               if self["menulist"].getCurrent()[1] == 'restart':
+                       self["description"].setText(_("Restart your network connection and interfaces.\n" ) + self.oktext )
+
        def up(self):
                self["menulist"].up()
+               self.loadDescription()
+
        def down(self):
                self["menulist"].down()
+               self.loadDescription()
+
        def left(self):
                self["menulist"].pageUp()
+               self.loadDescription()
+
        def right(self):
                self["menulist"].pageDown()
+               self.loadDescription()
+
        def ok(self):
+               self.cleanup()
                if self["menulist"].getCurrent()[1] == 'setting':
                        self.session.openWithCallback(self.checklist, WlanConfig, self.iface)
                elif self["menulist"].getCurrent()[1] == 'scanap':
-                       self.session.open(WlanScanAp, self.iface)
+                       self.session.openWithCallback(self.WlanScanApCallback, WlanScanAp, self.iface)
                elif self["menulist"].getCurrent()[1] == 'dns':
                        self.session.open(NameserverSetup)
                elif self["menulist"].getCurrent()[1] == 'status':
@@ -163,7 +278,7 @@ class WlanSetup(Screen,HelpableScreen):
                elif self["menulist"].getCurrent()[1] == 'test':
                        self.session.openWithCallback(self.checklist,NetworkAdapterTest,self.iface)
                elif self["menulist"].getCurrent()[1] == 'restart':
-                       self.session.openWithCallback(self.restartNet, MessageBox, (_("Are you sure you want to restart your network interfaces?\n\n") + self.oktext ) )
+                       self.session.openWithCallback(self.restartLan, MessageBox, (_("Are you sure you want to restart your network interfaces?\n\n") + self.oktext ) )
 
        def checklist(self):
                self["menulist"].setList(self.MakeMenu())
@@ -172,89 +287,342 @@ class WlanSetup(Screen,HelpableScreen):
                menu = []
                menu.append((_("Adapter settings"), "setting"))
                menu.append((_("Scan Wireless AP"), "scanap"))
-               menu.append((_("Nameserver settings"), "dns"))
+#              menu.append((_("Nameserver settings"), "dns"))
                if iNetwork.getAdapterAttribute(self.iface, "up"):
                        menu.append((_("Show WLAN Status"), "status"))
                menu.append((_("Network test"), "test"))
                menu.append((_("Restart network"), "restart"))
 
                return menu
-               
-       def restartNet(self,ret = False):
-               if ret == True:
-                       os_system('/etc/init.d/networking restart')
-#              self.updateStatusbar()
-#              self.onLayoutFinish.append(self.layoutFinished)
-#              self.onClose.append(self.cleanup)
-
-wlanconfig = ConfigSubsection()
-wlanconfig.usedevice = ConfigSelection(default = "off", choices = [
-       ("off", _("off")), ("on", _("on"))])
-wlanconfig.usedhcp = ConfigSelection(default = "off", choices = [
-       ("off", _("no")), ("on", _("yes"))])
-wlanconfig.essid = ConfigSelection(default = "none", choices = ["none"])
-wlanconfig.encrypt = ConfigSelection(default = "off", choices = [
-       ("off", _("no")), ("on", _("yes"))])
-wlanconfig.method = ConfigSelection(default = "wep", choices = [
-       ("wep", _("WEP")), ("wpa", _("WPA")), ("wpa2", _("WPA2")),("wpa/wpa2", _("WPA/WPA2"))])
-wlanconfig.keytype = ConfigSelection(default = "ascii", choices = [
-       ("ascii", _("ASCII")), ("hex", _("HEX"))])
-wlanconfig.key = ConfigText(default = "XXXXXXXX", visible_width = 50, fixed_size = False)
-wlanconfig.usegateway = ConfigSelection(default = "off", choices = [
-       ("off", _("no")), ("on", _("yes"))])
-wlanconfig.ip   = ConfigIP([0,0,0,0])
-wlanconfig.netmask = ConfigIP([0,0,0,0])
-wlanconfig.gateway = ConfigIP([0,0,0,0])
-
-selectap = None        
+
+       def WlanScanApCallback(self, essid = None):
+               if essid is not None:
+                       self.session.openWithCallback(self.checklist, WlanConfig, self.iface)
+
+       def restartLan(self, ret = False):
+               if (ret == True):
+                       iNetwork.restartNetwork(self.restartLanDataAvail)
+                       self.restartLanRef = self.session.openWithCallback(self.restartfinishedCB, MessageBox, _("Please wait while your network is restarting..."), type = MessageBox.TYPE_INFO, enable_input = False)
+
+       def restartLanDataAvail(self, data):
+               if data is True:
+                       iNetwork.getInterfaces(self.getInterfacesDataAvail)
+
+       def getInterfacesDataAvail(self, data):
+               if data is True:
+                       self.restartLanRef.close(True)
+
+       def restartfinishedCB(self,data):
+               if data is True:
+                       self.session.open(MessageBox, _("Finished restarting your network"), type = MessageBox.TYPE_INFO, timeout = 5, default = False)
+
+       def cleanup(self):
+               iNetwork.stopRestartConsole()
+               iNetwork.stopGetInterfacesConsole()
+
+ESSID_SELECTED_IN_APLIST = None
+CHECK_NETWORK_SHARE = False
+
 class WlanConfig(Screen, ConfigListScreen, HelpableScreen):
-       skin = """
-       <screen name="WlanConfig" position="209,48" size="865,623" title="Wireless Network Configuration..." flags="wfNoBorder" backgroundColor="transparent">  
-               <ePixmap pixmap="Vu_HD/Bg_EPG_view.png" zPosition="-1" position="0,0" size="865,623" alphatest="on" />
-               <ePixmap pixmap="Vu_HD/menu/ico_title_Setup.png" position="32,41" size="40,40" alphatest="blend"  transparent="1" />
-               <eLabel text="Wireless Network Configuration..." position="90,50" size="600,32" font="Semiboldit;32" foregroundColor="#5d5d5d" backgroundColor="#27b5b9bd" transparent="1" />
-               <ePixmap pixmap="Vu_HD/icons/clock.png" position="750,55" zPosition="1" size="20,20" alphatest="blend" />
-               <widget source="global.CurrentTime" render="Label" position="770,57" zPosition="1" size="50,20" font="Regular;20" foregroundColor="#1c1c1c" backgroundColor="#27d9dee2" halign="right" transparent="1">
-                       <convert type="ClockToText">Format:%H:%M</convert>
-               </widget>
-               <ePixmap pixmap="Vu_HD/buttons/red.png" position="45,98" size="25,25" alphatest="blend" />
-               <widget source="key_red" render="Label" position="66,97" zPosition="1" size="150,25" font="Regular;20" halign="center" valign="center" backgroundColor="darkgrey" foregroundColor="#1c1c1c" transparent="1" />
-               <ePixmap pixmap="Vu_HD/border_menu.png" position="120,140" zPosition="-1" size="342,358" transparent="1" alphatest="blend" />
-               <widget name="config" position="130,150" size="322,338" transparent="1" backgroundColor="#27d9dee2" zPosition="10" scrollbarMode="showOnDemand" />
-               <eLabel text="IP Address : " position="500,160" size="200,26" font="Semiboldit;22" foregroundColor="#5d5d5d" backgroundColor="#27b5b9bd" transparent="1" />             
-               <widget source="ipaddress" render="Label" position="530,190" zPosition="1" size="150,26" font="Regular;20" halign="center" valign="center" backgroundColor="#27b5b9bd" foregroundColor="#1c1c1c" transparent="1" />             
-               <eLabel text="NetMask : " position="500,220" size="200,26" font="Semiboldit;22" foregroundColor="#5d5d5d" backgroundColor="#27b5b9bd" transparent="1" />                
-               <widget source="netmask" render="Label" position="530,250" zPosition="1" size="150,26" font="Regular;20" halign="center" valign="center" backgroundColor="#27b5b9bd" foregroundColor="#1c1c1c" transparent="1" />               
-               <eLabel text="Gateway : " position="500,280" size="200,26" font="Semiboldit;22" foregroundColor="#5d5d5d" backgroundColor="#27b5b9bd" transparent="1" />                
-               <widget source="gateway" render="Label" position="530,310" zPosition="1" size="150,26" font="Regular;20" halign="center" valign="center" backgroundColor="#27b5b9bd" foregroundColor="#1c1c1c" transparent="1" />               
-       </screen>"""
+       skin =  """
+               <screen position="center,center" size="510,400" title="Wireless Network Configuration..." >
+                       <ePixmap pixmap="skin_default/buttons/red.png" position="10,360" size="140,40" alphatest="on" />
+                       <ePixmap pixmap="skin_default/buttons/green.png" position="360,360" size="140,40" alphatest="on" />
+
+                       <widget source="key_red" render="Label" position="10,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
+                       <widget source="key_green" render="Label" position="360,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />
+
+                       <widget name="config" position="10,10" backgroundColor="#371e1c1a" transparent="1" size="480,195" scrollbarMode="showOnDemand" />
+                       <ePixmap pixmap="skin_default/div-h.png" position="0,210" zPosition="1" size="560,2" />
+                       <widget source="ipaddresstext" render="Label" position="100,220" zPosition="1" size="190,21" font="Regular;19" halign="Left" valign="center" />
+                       <widget source="ipaddress" render="Label" position="300,220" zPosition="1" size="150,26" font="Regular;20" halign="Left" valign="center" />
+                       <widget source="netmasktext" render="Label" position="100,245" zPosition="1" size="190,21" font="Regular;19" halign="Left" valign="center" />
+                       <widget source="netmask" render="Label" position="300,245" zPosition="1" size="150,26" font="Regular;20" halign="Left" valign="center" />
+                       <widget source="gatewaytext" render="Label" position="100,270" zPosition="1" size="190,21" font="Regular;19" halign="Left" valign="center" />
+                       <widget source="gateway" render="Label" position="300,270" zPosition="1" size="150,26" font="Regular;20" halign="Left" valign="center" />
+                       <widget source="DNS1text" render="Label" position="100,295" zPosition="1" size="190,21" font="Regular;19" halign="Left" valign="center" />
+                       <widget source="DNS1" render="Label" position="300,295" zPosition="1" size="150,26" font="Regular;20" halign="Left" valign="center" />
+                       <widget source="DNS2text" render="Label" position="100,320" zPosition="1" size="190,21" font="Regular;19" halign="Left" valign="center" />
+                       <widget source="DNS2" render="Label" position="300,320" zPosition="1" size="150,26" font="Regular;20" halign="Left" valign="center" />
+                       <widget name="VKeyIcon" pixmap="skin_default/buttons/key_text.png" position="460,230" zPosition="10" size="35,25" transparent="1" alphatest="on" />
+                       <widget name="HelpWindow" pixmap="skin_default/buttons/key_text.png" position="383,420" zPosition="1" size="1,1" transparent="1" alphatest="on" />
+               </screen>
+               """
        def __init__(self, session, iface):
                Screen.__init__(self,session)
                self.session = session
-               self.mainmenu = []
-               self["key_red"] = StaticText(_("Close"))                
+               self["key_red"] = StaticText(_("Close"))
+               self["key_green"] = StaticText(_("Ok"))
+               self["ipaddresstext"] = StaticText(_("IP Address"))
                self["ipaddress"] = StaticText(_("[ N/A ]"))
-               self["netmask"] = StaticText(_("[ N/A ]"))              
+               self["netmasktext"] = StaticText(_("NetMask"))
+               self["netmask"] = StaticText(_("[ N/A ]"))
+               self["gatewaytext"] = StaticText(_("Gateway"))
                self["gateway"] = StaticText(_("[ N/A ]"))
+               self["DNS1text"] = StaticText(_("Primary DNS"))
+               self["DNS1"] = StaticText(_("[ N/A ]"))
+               self["DNS2text"] = StaticText(_("Secondary DNS"))
+               self["DNS2"] = StaticText(_("[ N/A ]"))
                self["OkCancelActions"] = ActionMap(["ShortcutActions", "SetupActions" ],
                {
-                       "ok": self.ok,
-                       "cancel": self.close,
-                       "red": self.close,
+                       "ok": self.saveWlanConfig,
+                       "green": self.saveWlanConfig,
+                       "cancel": self.keyCancel,
+                       "red": self.keyCancel,
                }, -2)
+               self["HelpWindow"] = Pixmap()
+               self["HelpWindow"].hide()
+               self["VKeyIcon"] = Pixmap()
+               self["VKeyIcon"].hide()
                self.iface = iface
-               self.ssid = None
-               self.scan_ssid = None
-               self.key_mgmt = None
-               self.proto = None
-               self.key_type = None
-               self.wep_key = None
-               
+
                self.list = []
-               self.wlanscanap = None
-               ConfigListScreen.__init__(self, self.list,session = self.session)
-               self.readifSetting()
+               ConfigListScreen.__init__(self, self.list, session = self.session)
+               self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
+
+               self.updateInterfaces(self.updateInterfaceCB)
+               self.onClose.append(self.cleanup)
 
+       def updateInterfaces(self,callback = None):
+               iNetwork.config_ready = False
+               iNetwork.msgPlugins()
+               iNetwork.getInterfaces(callback)
+
+       def updateInterfaceCB(self, ret=None):
+               if ret is not True:
+                       print "getInterfaces Fail... "
+
+               self.createConfig()
+               self.createSetup()
+
+       def getWpaSupplicantName(self, iface):
+               return "/etc/wpa_supplicant.conf.%s" % iface
+
+       def readWpaSupplicantConf(self):
+               wpaSupplicantName = self.getWpaSupplicantName(self.iface)
+               wsconf = {}
+               try:
+                       if fileExists(wpaSupplicantName):
+                               wpafd = open(wpaSupplicantName, "r")
+                               lines = wpafd.readlines()
+                               wpafd.close()
+                               data = {}
+                               for line in lines:
+                                       try:
+                                               (key, value) = line.strip().split('=',1)
+                                       except:
+                                               continue
+
+#                                      if key not in ('ssid', 'ap_scan', 'scan_ssid', 'key_mgmt', 'proto', 'wep_key0', 'psk', '#psk'):
+                                       if key not in ('ssid', 'scan_ssid', 'key_mgmt', 'proto', 'wep_key0', 'psk', '#psk'):
+                                               continue
+
+                                       elif key == 'ssid':
+                                               data[key] = value.strip('"')
+
+                                       else:
+                                               data[key] = value.strip()
+
+                               wsconf["ssid"] = data.get("ssid", "INPUTSSID")
+                               wsconf["hidden_ssid"] = data.get("scan_ssid") == '1' and True or False
+
+                               key_mgmt = data.get("key_mgmt")
+                               if key_mgmt == "NONE":
+                                       wep_key = data.get("wep_key0")
+
+                                       if wep_key is None:
+                                               wsconf["encrypt_mothod"] = "None"
+                                       else:
+                                               wsconf["encrypt_mothod"] = "wep"
+
+                                               if wep_key.startswith('"') and wep_key.endswith('"'):
+                                                       wsconf["wep_keytype"] = "ascii"
+                                                       wsconf["key"] = wep_key.strip('"')
+                                               else:
+                                                       wsconf["wep_keytype"] = "hex"
+                                                       wsconf["key"] = wep_key
+
+                               elif key_mgmt == "WPA-PSK":
+                                       proto = data.get("proto")
+
+                                       if proto == "WPA":
+                                               wsconf["encrypt_mothod"] = "wpa"
+
+                                       elif proto == "RSN":
+                                               wsconf["encrypt_mothod"] = "wpa2"
+
+                                       elif proto in ( "WPA RSN", "WPA WPA2"):
+                                               wsconf["encrypt_mothod"] = "wpa/wpa2"
+
+                                       else:
+                                               wsconf["encrypt_mothod"] = "wpa2"
+
+                                       psk = data.get("#psk")
+                                       if psk:
+                                               wsconf["key"] = psk.strip('"')
+                                       else:
+                                               wsconf["key"] = data.get("psk")
+                               else:
+                                       wsconf["encrypt_mothod"] = "wpa2"
+               except:
+                       pass
+
+               if wsconf.get("ssid") is None:
+                       wsconf["ssid"] = "INPUTSSID"
+               if wsconf.get("hidden_ssid") is None:
+                       wsconf["hidden_ssid"] = False
+               if wsconf.get("encrypt_mothod") is None:
+                       wsconf["encrypt_mothod"] = "wpa2"
+               if wsconf.get("wep_keytype") is None:
+                       wsconf["wep_keytype"] = "ascii"
+               if wsconf.get("key") is None:
+                       wsconf["key"] = "XXXXXXXX"
+
+#              print ""
+#              for (k,v) in wsconf.items():
+#                      print "[wsconf][%s] %s" % (k , v)
+
+               return wsconf
+
+       def displayIP(self, domain, entry):
+               text = entry.getText()
+               if text is not None and text != "0.0.0.0":
+                       self[domain].setText(entry.getText())
+               else:
+                       self[domain].setText(_("N/A"))
+
+       def createConfig(self):
+# activate Interface setup
+               self.activateInterfaceEntry = NoSave(ConfigYesNo(default=iNetwork.getAdapterAttribute(self.iface, "up") or False))
+# dhcp setup
+               self.usedhcpConfigEntry = NoSave(ConfigYesNo(default=iNetwork.getAdapterAttribute(self.iface, "dhcp") or False))
+
+# gateway setup
+               if iNetwork.getAdapterAttribute(self.iface, "gateway"):
+                       usegatewayDefault=True
+               else:
+                       usegatewayDefault=False
+               self.usegatewayConfigEntry = NoSave(ConfigYesNo(default=usegatewayDefault))
+
+               self.gatewayConfigEntry = NoSave(ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "gateway") or [0,0,0,0]))
+
+# IP, Netmask setup
+               self.IPConfigEntry = NoSave(ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "ip") or [0,0,0,0]))
+               self.netmaskConfigEntry = NoSave(ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "netmask") or [255,0,0,0]))
+
+# DNS setup
+               if iNetwork.getAdapterAttribute(self.iface, "dns-nameservers"):
+                       dnsDefault = True
+               else:
+                       dnsDefault = False
+               self.useDNSConfigEntry = NoSave(ConfigYesNo(default=dnsDefault or False))
+
+               nameserver = (iNetwork.getNameserverList() + [[0,0,0,0]] * 2)[0:2]
+               self.primaryDNS = NoSave(ConfigIP(default=nameserver[0]))
+               self.secondaryDNS = NoSave(ConfigIP(default=nameserver[1]))
+
+               self.displayIP("ipaddress", self.IPConfigEntry)
+               self.displayIP("netmask", self.netmaskConfigEntry)
+               self.displayIP("gateway", self.gatewayConfigEntry)
+               self.displayIP("DNS1", self.primaryDNS)
+               self.displayIP("DNS2", self.secondaryDNS)
+
+# readWPASupplicantConf
+               wsconf = self.readWpaSupplicantConf()
+
+# method setup
+               encryptionChoices = [("wep", _("WEP")), ("wpa", _("WPA")), ("wpa2", _("WPA2")), ("wpa/wpa2", _("WPA/WPA2")), ("None", _("No Encrypt"))  ]
+               self.methodConfigEntry = NoSave(ConfigSelection(default = wsconf["encrypt_mothod"], choices = encryptionChoices))
+
+# key type setup
+               keytypeChoices = [("ascii", _("ASCII")), ("hex", _("HEX"))]
+               self.keytypeConfigEntry = NoSave(ConfigSelection(default = wsconf["wep_keytype"], choices = keytypeChoices))
+
+# key setup
+               self.keyConfigEntry = NoSave(ConfigPassword(default = wsconf["key"], visible_width = 50, fixed_size = False))
+
+# hidden ssid setup
+               self.hiddenssidConfigEntry = NoSave(ConfigYesNo(default = wsconf["hidden_ssid"]))
+
+# ssid setup
+
+               global ESSID_SELECTED_IN_APLIST
+               if ESSID_SELECTED_IN_APLIST:
+                       essidDefault = ESSID_SELECTED_IN_APLIST
+               else:
+                       essidDefault = wsconf["ssid"]
+
+               self.ssidConfigEntry = NoSave(ConfigText(default = essidDefault, visible_width = 50, fixed_size = False))
+
+       def createSetup(self):
+               self.configList=[]
+               self.usedeviceEntry = getConfigListEntry(_("Use Device"), self.activateInterfaceEntry)
+               self.usedhcpEntry = getConfigListEntry(_("Use DHCP"), self.usedhcpConfigEntry)
+               self.essidEntry = getConfigListEntry(_("SSID"), self.ssidConfigEntry)
+               self.hiddenessidEntry = getConfigListEntry(_("Hidden Network"), self.hiddenssidConfigEntry)
+               self.methodEntry = getConfigListEntry(_("Encrypt Method"), self.methodConfigEntry)
+               self.keytypeEntry = getConfigListEntry(_("Key Type"), self.keytypeConfigEntry)
+               self.keyEntry = getConfigListEntry(_("KEY"), self.keyConfigEntry)
+
+               self.ipEntry = getConfigListEntry(_("IP"), self.IPConfigEntry)
+               self.netmaskEntry = getConfigListEntry(_("NetMask"), self.netmaskConfigEntry)
+
+               self.usegatewayEntry = getConfigListEntry(_("Use Gateway"), self.usegatewayConfigEntry)
+               self.gatewayEntry = getConfigListEntry(_("Gateway"), self.gatewayConfigEntry)
+
+               manualNameservers = (iNetwork.getInterfacesNameserverList(self.iface) + [[0,0,0,0]] * 2)[0:2]
+               self.manualPrimaryDNS = NoSave(ConfigIP(default=manualNameservers[0]))
+               self.manualSecondaryDNS = NoSave(ConfigIP(default=manualNameservers[1]))
+
+               self.usednsEntry =  getConfigListEntry(_("Use Manual dns-nameserver"), self.useDNSConfigEntry)
+               self.primaryDNSConfigEntry = getConfigListEntry(_('Primary DNS'), self.manualPrimaryDNS)
+               self.secondaryDNSConfigEntry = getConfigListEntry(_('Secondary DNS'), self.manualSecondaryDNS)
+
+               self.configList.append( self.usedeviceEntry )
+               if self.activateInterfaceEntry.value is True:
+                       self.configList.append( self.usedhcpEntry )
+
+                       if self.usedhcpConfigEntry.value is True:
+                               self.configList.append(self.usednsEntry)
+                       else:
+                               self.configList.append(self.ipEntry)
+                               self.configList.append(self.netmaskEntry)
+                               self.configList.append(self.usegatewayEntry)
+
+                               if self.usegatewayConfigEntry.value is True:
+                                       self.configList.append(self.gatewayEntry)
+
+                       if self.useDNSConfigEntry.value is True or self.usedhcpConfigEntry.value is False:
+                               self.configList.append(self.primaryDNSConfigEntry)
+                               self.configList.append(self.secondaryDNSConfigEntry)
+
+                       self.configList.append( self.hiddenessidEntry )
+                       self.configList.append( self.essidEntry )
+                       self.configList.append( self.methodEntry )
+
+                       if self.methodConfigEntry.value =="wep":
+                               self.configList.append( self.keytypeEntry )
+                       if self.methodConfigEntry.value != "None":
+                               self.configList.append( self.keyEntry )
+
+               self["config"].list = self.configList
+               self["config"].l.setList(self.configList)
+               if not self.showTextIcon in self["config"].onSelectionChanged:
+                       self["config"].onSelectionChanged.append(self.showTextIcon)
+
+       def showTextIcon(self):
+               if isinstance(self["config"].getCurrent()[1], ConfigText) or isinstance(self["config"].getCurrent()[1], ConfigPassword):
+                       self["VKeyIcon"].show()
+               else:
+                       self["VKeyIcon"].hide()
+
+       def onSelectHelpWindow(self, ret = False):
+               if isinstance(self["config"].getCurrent()[1], ConfigText) or isinstance(self["config"].getCurrent()[1], ConfigPassword):
+                       self["config"].getCurrent()[1].onSelect(self.session)
+
+       def onDeselectHelpWindow(self, ret = False):
+               if isinstance(self["config"].getCurrent()[1], ConfigText) or isinstance(self["config"].getCurrent()[1], ConfigPassword):
+                       self["config"].getCurrent()[1].onDeselect(self.session)
 
        def keyLeft(self):
                ConfigListScreen.keyLeft(self)
@@ -264,27 +632,68 @@ class WlanConfig(Screen, ConfigListScreen, HelpableScreen):
                ConfigListScreen.keyRight(self)
                self.newConfig()
 
+       def newConfig(self):
+               if self["config"].getCurrent() == self.usedeviceEntry or self["config"].getCurrent() == self.usedhcpEntry \
+                       or self["config"].getCurrent() == self.usegatewayEntry or self["config"].getCurrent() == self.methodEntry \
+                       or self["config"].getCurrent() == self.methodEntry or self["config"].getCurrent() == self.usednsEntry:
+                       self.createSetup()
 
-       def ok(self):
-               if self["config"].isChanged():
-                       self.session.openWithCallback(self.confirmactive, MessageBox, (_("Are you sure you want to restart your network interfaces?\n") ) )
+       def saveWlanConfig(self):
+               try:
+                       self.onDeselectHelpWindow()
+
+                       if self["config"].isChanged():
+                               self.session.openWithCallback(self.checkNetworkConfig, MessageBox, (_("Are you sure you want to restart your network interfaces?\n") ) )
+                       else:
+                               self.session.openWithCallback(self.checkNetworkConfig, MessageBox, (_("Network configuration is not changed....\n\nAre you sure you want to restart your network interfaces?\n") ) )
+               except:
+                       pass
 
-       def confirmactive(self, ret = False):
+       def checkNetworkConfig(self, ret = False):
                if ret == False:
-                       return
+                       self.onSelectHelpWindow()
+
+               elif len(self.ssidConfigEntry.value) == 0:
+                       self.session.open(MessageBox, ("PLEASE INPUT SSID"), type = MessageBox.TYPE_ERROR, timeout = 10)
+
+               elif len(self.keyConfigEntry.value) == 0:
+                       self.session.open(MessageBox, ("PLEASE INPUT ENCRYPT KEY"), type = MessageBox.TYPE_ERROR, timeout = 10)
+
                else:
-                       num_configured_if = len(iNetwork.getConfiguredAdapters())
-                       if num_configured_if >= 1:
-                               if num_configured_if == 1 and self.iface in iNetwork.getConfiguredAdapters():
-                                       self.saveif(False)
-                               else:
-                                       self.session.openWithCallback(self.saveif, MessageBox, (_("Are you sure you want to deactive another network interfaces?\n") ) )
+                       global CHECK_NETWORK_SHARE
+                       if CHECK_NETWORK_SHARE:
+                               self.checkNetworkShares(self.confirmAnotherIfaces)
+                       else:
+                               self.confirmAnotherIfaces()
+
+       def checkNetworkShares(self, callback):
+               cmd = "cat /proc/mounts"
+               data = popen(cmd).readlines()
+               networks = ['nfs','smbfs','ncp','coda']
+               for line in data:
+                       split = line.strip().split(' ',3)
+                       if split[2] in networks:
+                               self.session.openWithCallback(self.onSelectHelpWindow, MessageBox, ("NOT deconfiguring network interfaces :\n network shares still mounted\n"), type = MessageBox.TYPE_ERROR, timeout = 10)
+                               return
+               callback()
+
+       def confirmAnotherIfaces(self):
+               num_configured_if = len(iNetwork.getConfiguredAdapters())
+               if num_configured_if >= 1:
+                       if num_configured_if == 1 and self.iface in iNetwork.getConfiguredAdapters():
+                               self.confirmAnotherIfacesCB(False)
                        else:
-                               self.saveif(False)
-                               
-       def saveif(self,ret = False):
-               self["OkCancelActions"].setEnabled(False)
-               self["config_actions"].setEnabled(False)
+                               self.session.openWithCallback(self.confirmAnotherIfacesCB, MessageBox, _("A second configured interface has been found.\n\nDo you want to disable the second network interface?"), default = True)
+               else:
+                       self.confirmAnotherIfacesCB(False)
+
+       def isWPAMethod(self, method):
+               if method in ("wep", "None"):
+                       return False
+               else:
+                       return True
+
+       def confirmAnotherIfacesCB(self, ret):
                if ret == True:
                        configuredInterfaces = iNetwork.getConfiguredAdapters()
                        for interface in configuredInterfaces:
@@ -292,521 +701,423 @@ class WlanConfig(Screen, ConfigListScreen, HelpableScreen):
                                        continue
                                iNetwork.setAdapterAttribute(interface, "up", False)
                                iNetwork.deactivateInterface(interface)
-               wpafd = open("/etc/wpa_supplicant.conf","w")
-               if wpafd > 0:
-                       contents = "#WPA Supplicant Configuration by enigma2\n"
-                       contents += "ctrl_interface=/var/run/wpa_supplicant\n"
-                       contents += "eapol_version=1\n"
-                       contents += "fast_reauth=1\n"
-                       contents += "ap_scan=1\n"
-                       contents += "network={\n"
-                       contents += "\tssid=\""+wlanconfig.essid.value+"\"\n"
-                       contents += "\tscan_ssid=0\n"
-                       if wlanconfig.encrypt.value == "on":
-                               if wlanconfig.method.value =="wep":
-                                       contents += "\tkey_mgmt=NONE\n"
-                                       contents += "\twep_key0="
-                               elif wlanconfig.method.value == "wpa":
-                                       contents += "\tkey_mgmt=WPA-PSK\n"
-                                       contents += "\tproto=WPA\n"
-                                       contents += "\tpairwise=CCMP TKIP\n"
-                                       contents += "\tgroup=CCMP TKIP\n"
-                                       contents += "\tpsk="                                    
-                               elif wlanconfig.method.value == "wpa2":
-                                       contents += "\tkey_mgmt=WPA-PSK\n"
-                                       contents += "\tproto=WPA RSN\n"
-                                       contents += "\tpairwise=CCMP TKIP\n"
-                                       contents += "\tgroup=CCMP TKIP\n"
-                                       contents += "\tpsk="
-                               elif wlanconfig.method.value == "wpa/wpa2":
-                                       contents += "\tkey_mgmt=WPA-PSK\n"
-                                       contents += "\tproto=WPA WPA2\n"
-                                       contents += "\tpairwise=CCMP TKIP\n"
-                                       contents += "\tgroup=CCMP TKIP\n"
-                                       contents += "\tpsk="
-                               if wlanconfig.keytype.value == "ascii":
-                                       contents += "\""+wlanconfig.key.value+"\"\n"            
-                               else:
-                                       contents += wlanconfig.key.value+"\n"
-                       else:
-                               contents += "\tkey_mgmt=NONE\n"                 
-                       contents += "}\n"
-                       print "content = \n"+contents
-                       wpafd.write(contents)
-                       wpafd.close()
-               iffd = open("/etc/network/interfaces","r")
-               if iffd > 0:
-                       prev_content = ""
-                       next_content = ""
-                       data = iffd.readline()
-                       status = 0
-                       while len(data) >0 :
-                               if data.startswith('iface '+self.iface) or data.startswith('auto '+self.iface):
-                                       status = 1
-                                       data = iffd.readline()
-                                       continue
-                               elif not data.startswith('auto lo') and data.startswith('auto '):
-                                       if ret == True or data[5:] not in iNetwork.getConfiguredAdapters():
-                                               data = iffd.readline()
-                                               continue
-                               if status == 1 and data.startswith('iface ') or data.startswith('auto '):
-                                       status = 2
-                               if status == 0:
-                                       prev_content += data
-                               elif status == 2:
-                                       next_content += data
-                               data = iffd.readline()
-                       iffd.close()
-                       iffd = open("/etc/network/interfaces","w")
-                       if iffd > 0 :
-                               if prev_content == "":
-                                       prev_content = "# automatically generated by enigma2\n"
-                                       prev_content += "# do Not change manually!\n\n"
-                                       prev_content += "auto lo\n"
-                                       prev_content += "iface lo inet loopback\n\n"
-                               iffd.write(prev_content)
-                               if wlanconfig.usedevice.value=="on":
-                                       iNetwork.setAdapterAttribute(self.iface, "up", True)
-                                       contents = "auto "+self.iface+"\n"
-                                       contents += "iface "+self.iface+" inet "
-                                       if wlanconfig.usedhcp.value =="on":
-                                               iNetwork.setAdapterAttribute(self.iface, "dhcp", True)                                  
-                                               contents +="dhcp\n"
-                                       else:
-                                               iNetwork.setAdapterAttribute(self.iface, "dhcp", False)
-                                               contents +="static\n"
-                                               print wlanconfig.ip.value
-                                               iNetwork.setAdapterAttribute(self.iface, "ip", wlanconfig.ip.value)
-                                               iNetwork.setAdapterAttribute(self.iface, "netmask", wlanconfig.netmask.value)                                           
-                                               contents +="\taddress "+ self.formatip(wlanconfig.ip.value)+"\n"
-                                               contents +="\tnetmask "+ self.formatip(wlanconfig.netmask.value)+"\n"
-                                               if wlanconfig.usegateway.value == "on":
-                                                       iNetwork.setAdapterAttribute(self.iface, "gateway", wlanconfig.gateway.value)                   
-                                                       contents +="\tgateway "+ self.formatip(wlanconfig.gateway.value)+"\n"
-                                       contents += "\n\tpre-up /usr/sbin/wpa_supplicant -i"+self.iface+" -c/etc/wpa_supplicant.conf -B -D"+iNetwork.detectWlanModule(self.iface)+"\n"
-                                       contents += "\tpost-down wpa_cli terminate\n\n"
-                                       iffd.write(contents)
-                               else:
-                                       iNetwork.setAdapterAttribute(self.iface, "up", False)
-                                       iNetwork.deactivateInterface(self.iface)
-                               iffd.write(next_content)
-                               iffd.close()
-               self.restartNetwork(self.ConfigDataApply)
-               self.configurationmsg = self.session.openWithCallback(self.WlanConfigClose, MessageBox, _("Please wait for activation of your network configuration..."), type = MessageBox.TYPE_INFO, enable_input = False)
-
-       def restartNetwork(self,callback=None):
-               self.restartConsole = Console()
-               cmd="/etc/init.d/networking restart"
-               self.restartConsole.ePopen(cmd, self.restartNetworkFinished, callback)
-
-       def restartNetworkFinished(self, result, retval,extra_args):
-               ( callback ) = extra_args
-               if callback is not None:
-                       callback(True)
-
-       def ConfigDataApply(self,ret):
-               if ret is True:
-                       iNetwork.getInterfaces(self.configurationmsgClose)
 
-       def configurationmsgClose(self,ret):
-               if ret is True:
-                       self.configurationmsg.close(True)
-                       
-       def WlanConfigClose(self,ret):
-               if ret is True:
-                       self.close()
-       
-       def formatip(self, iplist):
-               list = []
-               list = iplist
-               try:
-                       if len(iplist) == 4:
-                               result = str(iplist[0])+"."+str(iplist[1])+"."+str(iplist[2])+"."+str(iplist[3])
-                       else:
-                               result ="0.0.0.0"
-                       return result
-               except:
-                       return "[N/A]"
-                       
-       def createConfig(self):
-#              wlanconfig.essid = ConfigSelection(default = "none", choices = ["maruap3","maruap2","none"])
-                       
-               self.tlist=[]
-               self.usedeviceEntry = getConfigListEntry(_("Use Device"), wlanconfig.usedevice)
-               self.usedhcpEntry = getConfigListEntry(_("Use DHCP"), wlanconfig.usedhcp)
-               self.essidEntry = getConfigListEntry(_("ESSID"), wlanconfig.essid)
-               self.encryptEntry = getConfigListEntry(_("Encrypt"), wlanconfig.encrypt)
-               self.methodEntry = getConfigListEntry(_("Method"), wlanconfig.method)
-               self.keytypeEntry = getConfigListEntry(_("Key Type"), wlanconfig.keytype)               
-               self.keyEntry = getConfigListEntry(_("KEY"), wlanconfig.key)
-
-               self.ipEntry = getConfigListEntry(_("IP"), wlanconfig.ip)
-               self.netmaskEntry = getConfigListEntry(_("NetMask"), wlanconfig.netmask)
-
-               self.usegatewayEntry = getConfigListEntry(_("Use Gateway"), wlanconfig.usegateway)
-               self.gatewayEntry = getConfigListEntry(_("Gateway"), wlanconfig.gateway)
-               
-               self.tlist.append( self.usedeviceEntry )
-               if wlanconfig.usedevice.value is "on":
-                       self.tlist.append( self.usedhcpEntry )
-                       if wlanconfig.usedhcp.value is "off":
-                               self.tlist.append(self.ipEntry)
-                               self.tlist.append(self.netmaskEntry)
-                               self.tlist.append(self.usegatewayEntry)
-                               if wlanconfig.usegateway.value is "on":
-                                       self.tlist.append(self.gatewayEntry)
-                       self.tlist.append( self.essidEntry )
-                       self.tlist.append( self.encryptEntry )
-                       if wlanconfig.encrypt.value is "on" :
-                               self.tlist.append( self.methodEntry )
-                               self.tlist.append( self.keytypeEntry )
-                               self.tlist.append( self.keyEntry )
-               
-               self["config"].list = self.tlist
-               self["config"].l.setList(self.tlist)
-               if not self.selectionChanged in self["config"].onSelectionChanged:
-                       self["config"].onSelectionChanged.append(self.selectionChanged)
+               if not self.isWPAMethod(self.methodConfigEntry.value):
+                       self.writeWpasupplicantConf()
+               else:
+                       self.getWpaPhrase()
+
+       def getWpaPhrase(self):
+               cmd = "wpa_passphrase '%s' %s" % (self.ssidConfigEntry.value, self.keyConfigEntry.value)
+#              print cmd
+               data = popen(cmd).readlines()
+               plainpwd = None
+               psk = None
+               for line in data:
+#                      print line,
+                       try:
+                               (key, value) = line.strip().split('=',1)
+                       except:
+                               continue
+
+                       if key == '#psk':
+                               plainpwd = line
+                       elif key == 'psk':
+                               psk = line
+               self.writeWpasupplicantConf(psk, plainpwd)
 
-       def readifSetting(self):
+       def writeWpasupplicantConf(self, passphrasekey=None, plainpwd=None):
+               wpaSupplicantName = self.getWpaSupplicantName(self.iface)
                try:
-                       if fileExists("/etc/wpa_supplicant.conf"):
-                               wpafd = open("/etc/wpa_supplicant.conf","r")
-                               if wpafd >0:
-                                       data = wpafd.readline()
-                                       while len(data) > 0:
-                                               data = data.lstrip()
-                                               if len(data) == 0:
-                                                       data = wpafd.readline()
-                                                       continue
-                                               if data.startswith('ssid=') and len(data) > 6:
-                                                       self.ssid = data[6:-2]
-                                               elif data.startswith('scan_ssid=') and len(data) > 10:
-                                                       self.scan_ssid = data[10:-1]
-                                               elif data.startswith('key_mgmt=') and len(data) > 9:
-                                                       self.key_mgmt = data[9:-1]
-                                               elif data.startswith('proto=') and len(data) > 6:
-                                                       self.proto = data[6:-1]
-                                               elif data.startswith('wep_key0="') and len(data) > 11:
-                                                       self.key_type = 1
-                                                       self.wep_key = data[10:-2]
-                                               elif data.startswith('wep_key0=') and len(data) > 9:
-                                                       self.key_type = 0
-                                                       self.wep_key = data[9:-1]
-                                               elif data.startswith('psk="') and len(data) > 6:
-                                                       self.key_type = 1
-                                                       self.wep_key = data[5:-2]
-                                               elif data.startswith('psk=') and len(data) > 4:
-                                                       self.key_type = 0
-                                                       self.wep_key = data[4:-1]
-                                                       
-                                               data = wpafd.readline()
-                                       print self.ssid,self.scan_ssid,self.key_mgmt,self.proto,self.key_type,self.wep_key
-                                       wpafd.close()
-                                       self.setfromread()
-                               else:
-                                       print 'read error'
-                       else:
-                               self.setfromread()
+                       wpafd = open(wpaSupplicantName, "w")
                except:
-                       print 'open error'
+                       self.session.open(MessageBox, _("%s open error." % wpaSupplicantName ), type = MessageBox.TYPE_ERROR, timeout = 10)
+                       return
 
-       def setfromread(self):
-               iNetwork.getInterfaces()
-               
-               if iNetwork.getAdapterAttribute(self.iface, "up") == True:
-                       default_tmp = "on"
+               contents = "#WPA Supplicant Configuration by STB\n"
+               contents += "ctrl_interface=/var/run/wpa_supplicant\n"
+               contents += "eapol_version=1\n"
+               contents += "fast_reauth=1\n"
+               contents += "ap_scan=1\n"
+               contents += "network={\n"
+# ssid
+               contents += "\tssid=\""+self.ssidConfigEntry.value+"\"\n"
+# hidden ssid
+               if self.hiddenssidConfigEntry.value is True:
+                       contents += "\tscan_ssid=1\n"
                else:
-                       default_tmp = "off"
-               wlanconfig.usedevice = ConfigSelection(default=default_tmp, choices = [
-                       ("off", _("off")), ("on", _("on"))])
-               if iNetwork.getAdapterAttribute(self.iface, "dhcp"):
-                       default_tmp = "on"
-               else:
-                       default_tmp = "off"
-               wlanconfig.usedhcp = ConfigSelection(default=default_tmp, choices = [
-                       ("off", _("no")), ("on", _("yes"))])
-               wlanconfig      .ip = ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "ip")) or [0,0,0,0]
-               wlanconfig.netmask = ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "netmask") or [255,0,0,0])
-               if iNetwork.getAdapterAttribute(self.iface, "gateway"):
-                       default_tmp = "on"
-               else:
-                       default_tmp = "off"
-               wlanconfig.usegateway = ConfigSelection(default = default_tmp, choices = [
-                       ("off", _("no")), ("on", _("yes"))])
-               wlanconfig.gateway = ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "gateway") or [0,0,0,0])
+                       contents += "\tscan_ssid=0\n"
 
-               self["ipaddress"] = StaticText(_(self.formatip(iNetwork.getAdapterAttribute(self.iface, "ip"))))
-               self["netmask"] = StaticText(_(self.formatip(iNetwork.getAdapterAttribute(self.iface, "netmask"))))
-               self["gateway"] = StaticText(_(self.formatip(iNetwork.getAdapterAttribute(self.iface, "gateway"))))
+               if self.methodConfigEntry.value == "None":
+                       contents += "\tkey_mgmt=NONE\n"
+
+               elif self.methodConfigEntry.value == "wep":
+                       contents += "\tkey_mgmt=NONE\n"
+                       contents += "\twep_key0="
+                       if self.keytypeConfigEntry.value == "ascii":
+                               contents += "\""+self.keyConfigEntry.value+"\"\n"
+                       else:
+                               contents += self.keyConfigEntry.value+"\n"
 
-               if self.wep_key is not None:
-                       default_tmp = "on"
                else:
-                       default_tmp = "off"
-               wlanconfig.encrypt = ConfigSelection(default = default_tmp, choices = [
-                       ("off", _("no")), ("on", _("yes"))])
-
-               if self.key_mgmt=="NONE":
-                       default_tmp = "wep"
-               elif self.key_mgmt == "WPA-PSK":
-                       if self.proto == "WPA":
-                               default_tmp = "wpa"
-                       elif self.proto == "WPA RSN":
-                               default_tmp = "wpa2"
-                       elif self.proto == "WPA WPA2":
-                               default_tmp = "wpa/wpa2"
+                       if self.methodConfigEntry.value == "wpa":
+                               contents += "\tkey_mgmt=WPA-PSK\n"
+                               contents += "\tproto=WPA\n"
+                               contents += "\tpairwise=CCMP TKIP\n"
+                               contents += "\tgroup=CCMP TKIP\n"
+                       elif self.methodConfigEntry.value == "wpa2":
+                               contents += "\tkey_mgmt=WPA-PSK\n"
+                               contents += "\tproto=RSN\n"
+                               contents += "\tpairwise=CCMP TKIP\n"
+                               contents += "\tgroup=CCMP TKIP\n"
+                       else:
+                               contents += "\tkey_mgmt=WPA-PSK\n"
+                               contents += "\tproto=WPA RSN\n"
+                               contents += "\tpairwise=CCMP TKIP\n"
+                               contents += "\tgroup=CCMP TKIP\n"
+
+#                              print "plainpwd : ",plainpwd
+#                              print "passphrasekey : ",passphrasekey
+                       if plainpwd is not None and passphrasekey is not None:
+                               contents += plainpwd
+                               contents += passphrasekey
+                       else:
+                               contents += "\tpsk=%s\n" % self.keyConfigEntry.value
+
+               contents += "}\n"
+#              print "content = \n"+contents
+               wpafd.write(contents)
+               wpafd.close()
+               self.writeNetConfig()
+
+       def writeNetConfig(self):
+               if self.activateInterfaceEntry.value is True:
+                       iNetwork.setAdapterAttribute(self.iface, "up", True)
+                       if self.usedhcpConfigEntry.value is True:
+                               iNetwork.setAdapterAttribute(self.iface, "dhcp", True)
+                       else:
+                               iNetwork.setAdapterAttribute(self.iface, "dhcp", False)
+                               iNetwork.setAdapterAttribute(self.iface, "ip", self.IPConfigEntry.value)
+                               iNetwork.setAdapterAttribute(self.iface, "netmask", self.netmaskConfigEntry.value)
+                               if self.usegatewayConfigEntry.value is True:
+                                       iNetwork.setAdapterAttribute(self.iface, "gateway", self.gatewayConfigEntry.value)
+                       if self.useDNSConfigEntry.value is True or self.usedhcpConfigEntry.value is False:
+                               interfacesDnsLines = self.makeLineDnsNameservers([self.manualPrimaryDNS.value, self.manualSecondaryDNS.value])
+                               if interfacesDnsLines == "" :
+                                       interfacesDnsLines = False
+                               iNetwork.setAdapterAttribute(self.iface, "dns-nameservers", interfacesDnsLines)
                        else:
-                               default_tmp = "wpa"
+                               iNetwork.setAdapterAttribute(self.iface, "dns-nameservers", False)
                else:
-                       default_tmp = "wep"
-                       
-               wlanconfig.method = ConfigSelection(default = default_tmp, choices = [
-                       ("wep", _("WEP")), ("wpa", _("WPA")), ("wpa2", _("WPA2")),("wpa/wpa2", _("WPA/WPA2"))])
+                       iNetwork.setAdapterAttribute(self.iface, "up", False)
+                       iNetwork.deactivateInterface(self.iface)
+
+               wpaSupplicantName = self.getWpaSupplicantName(self.iface)
+               contents = "\tpre-up wpa_supplicant -i"+self.iface+" -c%s -B -D" % (wpaSupplicantName)  +iNetwork.detectWlanModule(self.iface)+"\n"
+               contents += "\tpost-down wpa_cli terminate\n"
+               iNetwork.setAdapterAttribute(self.iface, "configStrings", contents)
+               iNetwork.writeNetworkConfig()
+               iNetwork.restartNetwork(self.updateCurrentInterfaces)
+               self.configurationmsg = None
+               self.configurationmsg = self.session.openWithCallback(self.configFinished, MessageBox, _("Please wait for activation of your network configuration..."), type = MessageBox.TYPE_INFO, enable_input = False)
+
+       def makeLineDnsNameservers(self, nameservers = []):
+               line = "" 
+               entry = ' '.join([("%d.%d.%d.%d" % tuple(x)) for x in nameservers if x != [0, 0, 0, 0] ])
+               if len(entry):
+                       line+="\tdns-nameservers %s\n" % entry
+               return line
+
+       def updateCurrentInterfaces(self, ret):
+               if ret is True:
+                       iNetwork.getInterfaces(self.configurationMsgClose)
+               elif self.configurationmsg is not None:
+                       self.configurationmsg.close(False)
+
+       def configurationMsgClose(self,ret):
+               if self.configurationmsg is not None:
+                       if ret is True:
+                               self.configurationmsg.close(True)
+                       else:
+                               self.configurationmsg.close(False)
+
+       def configFinished(self,data):
+               if data is True:
+                       self.session.openWithCallback(self.configFinishedCB, MessageBox, _("Your network configuration has been activated."), type = MessageBox.TYPE_INFO, timeout = 10)
+                       global ESSID_SELECTED_IN_APLIST
+                       ESSID_SELECTED_IN_APLIST = None
+               else:
+                       self.session.openWithCallback(self.configFinishedCB, MessageBox, _("Network configuration is failed."), type = MessageBox.TYPE_INFO, timeout = 10)
+
+       def configFinishedCB(self, data):
+               if data is True:
+                       self.close()
                        
-               if self.key_type == 0:
-                       default_tmp = "hex"
+       def keyCancelConfirm(self, result):
+               if not result:
+                       self.onSelectHelpWindow()
+                       return
+
+               if self.oldInterfaceState is False:
+                       iNetwork.deactivateInterface(self.iface, self.keyCancelCB)
                else:
-                       default_tmp = "ascii"
-               wlanconfig.keytype = ConfigSelection(default = default_tmp, choices = [
-                       ("ascii", _("ASCII")), ("hex", _("HEX"))])                      
-               default_tmp = self.wep_key or "XXXXXXXX"
-               wlanconfig.key = ConfigText(default = default_tmp, visible_width = 50, fixed_size = False)
-               
-               if wlanconfig.usedevice.value is "on":
-                       self.getAplist()
+                       self.close()
+
+       def keyCancel(self,yesno = True):
+               if self["config"].isChanged():
+                       self.onDeselectHelpWindow()
+                       self.session.openWithCallback(self.keyCancelConfirm, MessageBox, _("Really close without saving settings?"))
                else:
-                       self.createConfig()
-               
+                       self.close()
 
-       def newConfig(self):
-               if self["config"].getCurrent() == self.usedeviceEntry :
-                       if wlanconfig.usedevice.value is "on":
-                               self.getAplist()
-                       else:
-                               if iNetwork.getAdapterAttribute(self.iface, "up"):
-                                       iNetwork.setAdapterAttribute(self.iface, "up",False)
-                                       iNetwork.deactivateInterface(self.iface)
-                               self.createConfig()
-               elif self["config"].getCurrent() == self.encryptEntry or self["config"].getCurrent() == self.usedhcpEntry \
-               or self["config"].getCurrent() == self.usegatewayEntry :
-                       self.createConfig()
-
-       def selectionChanged(self):
-               current = self["config"].getCurrent()
-               print current
-
-       def getAplist(self):
-               self["OkCancelActions"].setEnabled(False) #chang
-               self["config_actions"].setEnabled(False) #chang
-               if iNetwork.getAdapterAttribute(self.iface, "up") is not True:
-                       os_system('ifconfig '+self.iface+" up")
-                       iNetwork.setAdapterAttribute(self.iface, "up",True)
-                       time.sleep(1.5)
-               self.wlanscanap = Console()
-               cmd1 = "iwlist "+self.iface+" scan"
-               print 'cmd',cmd1
-               self.wlanscanap.ePopen(cmd1, self.iwlistfinnished,self.aplistparse)
-
-       def iwlistfinnished(self, result, retval,extra_args):
-               (statecallback) = extra_args
-               try:
-                       if self.wlanscanap is not None:
-                               if retval == 0:
-                                       self.wlanscanap = None
-                                       content = result.splitlines()
-                                       first = content[0].split()
-                                       completed = False
-                                       for x in first:
-                                               if x == 'completed':
-                                                       completed = True
-                                       if completed == True:
-                                               statecallback(result)
-                                       else:
-                                               statecallback(0)                                        
-                               else:
-                                       statecallback(0)
-               except:
+       def keyCancelCB(self,data):
+               if data is True:
                        self.close()
 
+       def cleanup(self):
+               iNetwork.stopRestartConsole()
+               iNetwork.stopGetInterfacesConsole()
+               iNetwork.stopDeactivateInterfaceConsole()
+
+SHOW_HIDDEN_NETWORK = False
+class WlanScanAp(Screen,HelpableScreen):
+       skin =  """
+               <screen position="center,center" size="510,400" title="Wireless Network AP Scan..." >
+                       <ePixmap pixmap="skin_default/div-h.png" position="0,350" zPosition="1" size="560,2" />
+                       <ePixmap pixmap="skin_default/border_menu.png" position="10,10" zPosition="1" size="250,300" transparent="1" alphatest="on" />
+
+                       <ePixmap pixmap="skin_default/buttons/red.png" position="10,360" size="140,40" alphatest="on" />
+                       <ePixmap pixmap="skin_default/buttons/green.png" position="185,360" size="140,40" alphatest="on" />
+                       <ePixmap pixmap="skin_default/buttons/blue.png" position="360,360" size="140,40" alphatest="on" />
+
+                       <widget source="key_red" render="Label" position="10,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
+                       <widget source="key_green" render="Label" position="185,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />
+                       <widget source="key_blue" render="Label" position="360,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" foregroundColor="#ffffff" transparent="1" />
+
+                       <widget name="aplist" position="20,20" size="230,275" backgroundColor="#371e1c1a" transparent="1" zPosition="10" scrollbarMode="showOnDemand" />
+
+                       <widget source="ESSID" render="Label" position="265,70" zPosition="1" size="240,30" font="Regular;18" halign="center" valign="center" />
+                       <widget source="Address" render="Label" position="265,100" zPosition="1" size="240,30" font="Regular;18" halign="center" valign="center" />
+                       <widget source="Protocol" render="Label" position="265,130" zPosition="1" size="240,30" font="Regular;18" halign="center" valign="center" />
+                       <widget source="Frequency" render="Label" position="265,160" zPosition="1" size="240,30" font="Regular;18" halign="center" valign="center" />
+                       <widget source="Channel" render="Label" position="265,190" zPosition="1" size="240,30" font="Regular;18" halign="center" valign="center" />
+                       <widget source="Encryption key" render="Label" position="265,220" zPosition="1" size="240,30" font="Regular;18" halign="center" valign="center" />
+                       <widget source="BitRate" render="Label" position="265,250" zPosition="1" size="240,30" font="Regular;18" halign="center" valign="center" />
+                       <widget source="Status" render="Label" position="115,310" zPosition="1" size="300,30" font="Regular;18" halign="center" valign="center" />
+               </screen>
+               """
 
-       def aplistparse(self,data):
-               global selectap
-               if data == 0:
-#                      self.session.openWithCallback(self.createConfig ,MessageBox, _("Scan AP Failed"), MessageBox.TYPE_INFO,2)               
-                       self.session.open(MessageBox, _("Scan AP Failed"), MessageBox.TYPE_INFO,2)      
-               else:
-                       self.aplist = []
-                       list = data.splitlines()
-#                      print 'aplistparse',list
-                       for x in list:
-                               xx = x.lstrip()
-                               if xx.startswith('ESSID:') and len(xx)>8:
-                                       self.aplist.append(xx[7:-1])
-#                      print 'rlist\n',rlist
-                       if len(self.aplist) ==0:
-                               self.aplist.append('none')
-#                      print 'aplist', self.aplist
-                       defaultap = None
-                       for x in self.aplist:
-                               if x == selectap:
-                                       defaultap = x
-                       print 'defaultap',defaultap,self.aplist,selectap
-                       if selectap is None and self.ssid is not None and self.ssid in self.aplist:
-                               wlanconfig.essid = ConfigSelection(default=self.ssid,choices = self.aplist)
-                       elif defaultap == selectap and selectap is not None:
-                               wlanconfig.essid = ConfigSelection(default=selectap,choices = self.aplist)
-                       else:
-                               wlanconfig.essid = ConfigSelection(choices = self.aplist)
-                       
-               self.createConfig()
-               self["OkCancelActions"].setEnabled(True)
-               self["config_actions"].setEnabled(True)
-               if iNetwork.getAdapterAttribute(self.iface, "up"):
-                       pass
-               else:
-                       os_system('ifconfig '+self.iface+" down")
-
-class WlanScanAp(Screen):
-       skin = """
-       <screen name="WlanScanAp" position="209,48" size="865,623" title="Wireless Network Scan..." flags="wfNoBorder" backgroundColor="transparent">   
-               <ePixmap pixmap="Vu_HD/Bg_EPG_view.png" zPosition="-1" position="0,0" size="865,623" alphatest="on" />
-               <ePixmap pixmap="Vu_HD/menu/ico_title_Setup.png" position="32,41" size="40,40" alphatest="blend"  transparent="1" />
-               <eLabel text="Wireless Network Scan..." position="90,50" size="600,32" font="Semiboldit;32" foregroundColor="#5d5d5d" backgroundColor="#27b5b9bd" transparent="1" />
-               <ePixmap pixmap="Vu_HD/icons/clock.png" position="750,55" zPosition="1" size="20,20" alphatest="blend" />
-               <widget source="global.CurrentTime" render="Label" position="770,57" zPosition="1" size="50,20" font="Regular;20" foregroundColor="#1c1c1c" backgroundColor="#27d9dee2" halign="right" transparent="1">
-                       <convert type="ClockToText">Format:%H:%M</convert>
-               </widget>
-               <ePixmap pixmap="Vu_HD/buttons/red.png" position="45,98" size="25,25" alphatest="blend" />
-               <widget source="key_red" render="Label" position="66,97" zPosition="1" size="150,25" font="Regular;20" halign="center" valign="center" backgroundColor="darkgrey" foregroundColor="#1c1c1c" transparent="1" />
-               <ePixmap pixmap="Vu_HD/border_menu.png" position="120,140" zPosition="-1" size="342,358" transparent="1" alphatest="blend" />
-               <widget name="menulist" position="130,150" size="322,338" transparent="1" backgroundColor="#27d9dee2" zPosition="10" scrollbarMode="showOnDemand" />
-               <widget source="ap_strength" render="Label" position="490,250" zPosition="1" size="300,30" font="Regular;20" halign="center" valign="center" backgroundColor="#27b5b9bd" foregroundColor="#1c1c1c" transparent="1" />           
-               <widget source="ap_quality" render="Label" position="490,280" zPosition="1" size="300,30" font="Regular;20" halign="center" valign="center" backgroundColor="#27b5b9bd" foregroundColor="#1c1c1c" transparent="1" />            
-       </screen>"""
        def __init__(self, session, iface):
                Screen.__init__(self,session)
+               HelpableScreen.__init__(self)
                self.session = session
-#              self.aplist = []
                self.iface = iface
-               self.mainmenu = []
-               self.ap_extra = []
-               self.ap_quality = []
                self.wlanscanap = None
-               self["OkCancelActions"] = ActionMap(["ShortcutActions", "SetupActions","WizardActions" ],
+               self.apList = {}
+               self.setApList = []
+
+               self["WizardActions"] = HelpableActionMap(self, "WizardActions",
                {
-                       "ok": self.ok,
-                       "cancel": self.close,
-                       "red": self.close,
-                       "up": self.up,
-                       "down": self.down,
-                       "left": self.left,
-                       "right": self.right,
+                       "up": (self.up, _("move up to previous entry")),
+                       "down": (self.down, _("move down to next entry")),
+                       "left": (self.left, _("move up to first entry")),
+                       "right": (self.right, _("move down to last entry")),
                }, -2)
-               self.getAplist()
-               print 'getAplist',self.mainmenu
-               self["menulist"] = MenuList(self.mainmenu)
+
+               self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
+               {
+                       "cancel": (self.close, _("exit")),
+                       "ok": (self.ok, "select AP"),
+               })
+
+               self["ColorActions"] = HelpableActionMap(self, "ColorActions",
+               {
+                       "red": (self.close, _("exit")),
+                       "green": (self.ok, "select AP"),
+                       "blue": (self.startWlanConfig, "Edit Wireless settings"),
+               })
+
+               self["aplist"] = MenuList(self.setApList)
                self["key_red"] = StaticText(_("Close"))
-               self["ap_strength"] = StaticText(_("Scanning AP List..")) 
-               self["ap_quality"] = StaticText(_("Wait a moment")) 
+               self["key_green"] = StaticText(_("Select"))
+               self["key_blue"] = StaticText(_("EditSetting"))
+               self["Status"] = StaticText(_(" "))
+               self["ESSID"] = StaticText(" ")
+               self["Address"] = StaticText(" ")
+               self["Protocol"] = StaticText(" ")
+               self["Frequency"] = StaticText(" ")
+               self["Channel"] = StaticText(" ")
+               self["Encryption key"] = StaticText(" ")
+               self["BitRate"] = StaticText(" ")
+               self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
+
+               self.startupTimer = eTimer()
+               self.startupTimer.callback.append(self.startup)
+
+               self.activateIfaceTimer = eTimer()
+               self.activateIfaceTimer.callback.append(self.activateIface)
+
+               self.updateStatusTimer = eTimer()
+               self.updateStatusTimer.callback.append(self.updateStatus)
                
+               self.scanAplistTimer = eTimer()
+               self.scanAplistTimer.callback.append(self.scanApList)
+               
+               self.apList = {}
+               self.onClose.append(self.__onClose)
+               self.onShown.append(lambda: self.startupTimer.start(10, True))
+
+       def startup(self):
+               if self.oldInterfaceState is not True:
+                       self["Status"].setText(("Please wait for activating interface..."))
+                       self.activateIfaceTimer.start(10, True)
+               else:
+                       self.updateStatusTimer.start(10, True)
+
+       def activateIface(self):
+               os_system("ifconfig "+self.iface+" up")
+               iNetwork.setAdapterAttribute(self.iface, "up", True)
+               self.updateStatusTimer.start(2000, True)
+               
+
+       def updateStatus(self):
+               self["Status"].setText(("Please wait for scanning AP..."))
+               self.scanAplistTimer.stop()
+               self.scanAplistTimer.start(10, True)
+
+       def updateAPList(self):
+               self.updateStatusTimer.stop()
+               self.updateStatusTimer.start(8000, True)
 
        def left(self):
-               self["menulist"].pageUp()
-               if len(self.ap_extra) > self["menulist"].getSelectionIndex():
-                       self["ap_strength"].setText((self.ap_extra[self["menulist"].getSelectionIndex()])+"%") 
-                       self["ap_quality"].setText(self.ap_quality[self["menulist"].getSelectionIndex()]) 
+               self["aplist"].pageUp()
+               self.displayApInfo()
        
        def right(self):
-               self["menulist"].pageDown()
-               if len(self.ap_extra) > self["menulist"].getSelectionIndex():
-                       self["ap_strength"].setText((self.ap_extra[self["menulist"].getSelectionIndex()])+"%") 
-                       self["ap_quality"].setText(self.ap_quality[self["menulist"].getSelectionIndex()]) 
+               self["aplist"].pageDown()
+               self.displayApInfo()
 
        def up(self):
-               self["menulist"].up()
-               if len(self.ap_extra) > self["menulist"].getSelectionIndex():
-                       self["ap_strength"].setText((self.ap_extra[self["menulist"].getSelectionIndex()])+"%") 
-                       self["ap_quality"].setText(self.ap_quality[self["menulist"].getSelectionIndex()]) 
+               self["aplist"].up()
+               self.displayApInfo()
                
        def down(self):
-               self["menulist"].down()
-               if len(self.ap_extra) > self["menulist"].getSelectionIndex():
-                       self["ap_strength"].setText((self.ap_extra[self["menulist"].getSelectionIndex()])+"%")
-                       self["ap_quality"].setText(self.ap_quality[self["menulist"].getSelectionIndex()])               
+               self["aplist"].down()
+               self.displayApInfo()
 
        def ok(self):
-               global selectap
-               ifaces=self["menulist"].getCurrent()
-               print 'select', ifaces
-               selectap = ifaces
+               global ESSID_SELECTED_IN_APLIST
+               if self["aplist"].getCurrent() is not None:
+                       ESSID_SELECTED_IN_APLIST = self["aplist"].getCurrent()[0]
                self.close()
 
-       def getAplist(self):
-               self["OkCancelActions"].setEnabled(False)
-               if iNetwork.getAdapterAttribute(self.iface, "up"):
-                       pass
-               else:
-                       os_system('ifconfig '+self.iface+" up")
-                       time.sleep(1.5)
-               self.wlanscanap = Console()
-               cmd1 = "iwlist "+self.iface+" scan"
-               self.wlanscanap.ePopen(cmd1, self.iwlistfinnished,self.aplistparse)
-
-       def iwlistfinnished(self, result, retval,extra_args):
-               (statecallback) = extra_args
+       def startWlanConfig(self): # key blue
+               global ESSID_SELECTED_IN_APLIST
+               if self["aplist"].getCurrent() is not None:
+                       ESSID_SELECTED_IN_APLIST = self["aplist"].getCurrent()[0]
+                       self.close(True)
+
+       def getScanResult(self, wirelessObj):
+               Iwscanresult  = None
                try:
-                       if self.wlanscanap is not None:
-                               if retval == 0:
-                                       self.wlanscanap = None
-                                       content = result.splitlines()
-                                       first = content[0].split()
-                                       completed = False
-                                       for x in first:
-                                               if x == 'completed':
-                                                       completed = True
-                                       if completed == True:
-                                               statecallback(result)
-                                       else:
-                                               statecallback(0)                                        
-                               else:
-                                       statecallback(0)
+                       Iwscanresult  = wirelessObj.scan()
+               except IOError:
+                       print "%s Interface doesn't support scanning.."%self.iface
+               return Iwscanresult
+
+       def scanApList(self):
+               self.apList = {}
+               self.setApList = []
+
+               wirelessObj = Wireless(self.iface)
+               Iwscanresult=self.getScanResult(wirelessObj)
+
+               if Iwscanresult is None or len(Iwscanresult.aplist) == 0:
+                       self["Status"].setText(("NO AP detected"))
+                       return
+
+               try:
+                       (num_channels, frequencies) = wirelessObj.getChannelInfo()
                except:
-                       self.close()
+                       pass
 
+               index = 1
+               for ap in Iwscanresult:
+                       self.apList[index] = {}
+                       self.apList[index]["Address"] = ap.bssid
+                       if len(ap.essid) == 0:
+                               self.apList[index]["ESSID"] = None
+                       else:
+                               self.apList[index]["ESSID"] = ap.essid
+
+                       self.apList[index]["Protocol"] = ap.protocol
+                       self.apList[index]["Frequency"] = wirelessObj._formatFrequency(ap.frequency.getFrequency())
+                       try:
+                               self.apList[index]["Channel"] = frequencies.index(self.apList[index]["Frequency"]) + 1
+                       except:
+                               self.apList[index]["Channel"] = "Unknown"
+
+                       self.apList[index]["Quality"] = "%s/%s" % \
+                               ( ap.quality.quality, wirelessObj.getQualityMax().quality )
+                       self.apList[index]["Signal Level"] = "%s/%s" % \
+                               ( ap.quality.getSignallevel(), "100" )
+                       self.apList[index]["Noise Level"] = "%s/%s" % \
+                               ( ap.quality.getNoiselevel(), "100" )
+
+# get encryption key on/off
+                       key_status = "Unknown"
+                       if (ap.encode.flags & wifi_flags.IW_ENCODE_DISABLED):
+                               key_status = "off"
+                       elif (ap.encode.flags & wifi_flags.IW_ENCODE_NOKEY):
+                               if (ap.encode.length <= 0):
+                                       key_status = "on"
+                       self.apList[index]["Encryption key"] = key_status
+
+# get bitrate
+                       if len(ap.rate) > 0:
+                               if len(ap.rate[0]) > 0:
+                                       self.apList[index]["BitRate"] = wirelessObj._formatBitrate(ap.rate[0][0])
+                       else:
+                               self.apList[index]["BitRate"] = ""
+                       index += 1
+
+#              print self.apList
+
+               # update menu list
+               ap_index = 0
+               for (ap_index, ap_info) in self.apList.items():
+                       essid = ap_info.get("ESSID", None)
+                       if essid is None:
+                               global SHOW_HIDDEN_NETWORK
+                               if SHOW_HIDDEN_NETWORK:
+                                       essid = "# Hidden Network"
+                               else:
+                                       continue
+                       self.setApList.append( (essid, int(ap_index)) )
 
-       def aplistparse(self,data):
-               rlist = []
-               essid_on = 0
-               if data == 0:
-                       self.session.open(MessageBox, _("Scan AP Failed"), MessageBox.TYPE_INFO,2)
-                       self["menulist"].setList(rlist)
-               else:
-                       list = data.splitlines()
-                       for x in list:
-                               for xx in x.split():
-                                       if xx.startswith('ESSID:') and len(xx)>8:
-                                               rlist.append(xx[7:-1])
-                                               essid_on = 1
-                                       if essid_on == 1 and xx.startswith('Extra:SignalStrength=') and len(xx)>21:
-                                               self.ap_extra.append(xx[6:])
-                                       if essid_on == 1 and xx.startswith('%,LinkQuality:') and len(xx)>14:
-                                               self.ap_quality.append(xx[2:])
-                                               essid_pm = 0
-                       if len(rlist) >0:
-                               self["menulist"].setList(rlist)
-                               if len(self.ap_extra) > 0 and len(self.ap_quality) > 0:
-                                       self["ap_strength"].setText((self.ap_extra[self["menulist"].getSelectionIndex()])+"%")
-                                       self["ap_quality"].setText(self.ap_quality[self["menulist"].getSelectionIndex()]) 
+               self["aplist"].setList(self.setApList)
+#              print "menu aplist : ", self.setApList
+               self["Status"].setText(("%d AP detected" % len(self.setApList)))
+               self.displayApInfo()
+
+               self.updateAPList()
+
+       def displayApInfo(self):
+               if self["aplist"].getCurrent() is not None:
+                       index = self["aplist"].getCurrent()[1]
+                       for key in ["Address", "ESSID", "Protocol", "Frequency", "Encryption key", "BitRate", "Channel"]:
+                               if self.apList[index].has_key(key) and self.apList[index][key] is not None:
+                                       value = str(self.apList[index][key])
                                else:
-                                       self["ap_strength"].setText("Select AP")
-                                       self["ap_quality"].setText(" ")
-               if iNetwork.getAdapterAttribute(self.iface, "up"):
-                       pass
-               else:
-                       os_system('ifconfig '+self.iface+" down")
-               self["OkCancelActions"].setEnabled(True)
+                                       value = "None"
+                               self[key].setText(( "%s:  %s" % (key, value) )) 
 
-class NetworkAdapterTest(Screen):      
+       def __onClose(self):
+               if self.oldInterfaceState is not True:
+                       os_system("ifconfig "+self.iface+" down")
+                       iNetwork.setAdapterAttribute(self.iface, "up", False)
+
+class NetworkAdapterTest(Screen):
        def __init__(self, session,iface):
                Screen.__init__(self, session)
                self.iface = iface
@@ -1038,17 +1349,17 @@ class NetworkAdapterTest(Screen):
                self["infoshortcuts"].setEnabled(True)
                self["shortcuts"].setEnabled(False)
                if self.activebutton == 1: # Adapter Check
-                       self["InfoText"].setText(_("This test detects your configured LAN-Adapter."))
+                       self["InfoText"].setText(_("This test detects your configured Wireless LAN-Adapter."))
                        self["InfoTextBorder"].show()
                        self["InfoText"].show()
                        self["key_red"].setText(_("Back"))
                if self.activebutton == 2: #LAN Check
-                       self["InfoText"].setText(_("This test checks whether a network cable is connected to your LAN-Adapter.\nIf you get a \"disconnected\" message:\n- verify that a network cable is attached\n- verify that the cable is not broken"))
+                       self["InfoText"].setText(_("This test checks whether a network cable is connected to your Wireless LAN-Adapter."))
                        self["InfoTextBorder"].show()
                        self["InfoText"].show()
                        self["key_red"].setText(_("Back"))
                if self.activebutton == 3: #DHCP Check
-                       self["InfoText"].setText(_("This test checks whether your LAN Adapter is set up for automatic IP Address configuration with DHCP.\nIf you get a \"disabled\" message:\n - then your LAN Adapter is configured for manual IP Setup\n- verify thay you have entered correct IP informations in the AdapterSetup dialog.\nIf you get an \"enabeld\" message:\n-verify that you have a configured and working DHCP Server in your network."))
+                       self["InfoText"].setText(_("This test checks whether your Wireless LAN Adapter is set up for automatic IP Address configuration with DHCP.\nIf you get a \"disabled\" message:\n - then your Wireless LAN Adapter is configured for manual IP Setup\n- verify thay you have entered correct IP informations in the AdapterSetup dialog.\nIf you get an \"enabeld\" message:\n-verify that you have a configured and working DHCP Server in your network."))
                        self["InfoTextBorder"].show()
                        self["InfoText"].show()
                        self["key_red"].setText(_("Back"))
@@ -1063,7 +1374,8 @@ class NetworkAdapterTest(Screen):
                        self["InfoText"].show()
                        self["key_red"].setText(_("Back"))
                if self.activebutton == 6: # Edit Settings
-                       self.session.open(WlanConfig,self.iface)
+                       self.cleanup()
+                       self.session.open(WlanConfig, self.iface)
                        self["shortcuts"].setEnabled(True)              
                        self["infoshortcuts"].setEnabled(False)
 
@@ -1175,7 +1487,7 @@ class NetworkAdapterTest(Screen):
 
        def getInfoCB(self,status):
                if status is not None:
-                       if status == "No Connection" or status == "Not-Associated" or status == False:
+                       if status.startswith("No Connection") or status.startswith("Not-Associated") or status == False:
                                self["Network"].setForegroundColorNum(1)
                                self["Network"].setText(_("disconnected"))
                                self["NetworkInfo_Check"].setPixmapNum(1)
@@ -1188,6 +1500,7 @@ class NetworkAdapterTest(Screen):
                                                
        def cleanup(self):
                iNetwork.stopLinkStateConsole()
+               iNetwork.stopPingConsole()
                iNetwork.stopDNSConsole()
 
        def AccessPointInfo(self,iface):
@@ -1197,34 +1510,29 @@ class NetworkAdapterTest(Screen):
 
        def readAP(self,result,retval,extra_args):
                (callback) = extra_args
-               self.apState = False
+               self.apState = None
                if self.iwconfigConsole is not None:
                        if retval == 0:
                                self.iwconfigConsole = None
-                               content=result.splitlines()
-                               for x in content:
-                                       if 'Access Point' in x:
-                                               self.apState = x[x.find('Access Point')+len('Access Point'):].strip(':').strip()
-                               callback(self.apState)
+                               for content in result.splitlines():
+                                       if 'Access Point' in content:
+                                               self.apState = content.strip().split('Access Point: ')[1]
+                                               callback(self.apState)
+                                               return
+               callback(self.apState)
                
 class Wlanstatus(Screen):
-       skin = """
-       <screen name="Wlanstatus" position="209,48" size="865,623" title="Wireless Network Status..." flags="wfNoBorder" backgroundColor="transparent"> 
-               <ePixmap pixmap="Vu_HD/Bg_EPG_view.png" zPosition="-1" position="0,0" size="865,623" alphatest="on" />
-               <ePixmap pixmap="Vu_HD/menu/ico_title_Setup.png" position="32,41" size="40,40" alphatest="blend"  transparent="1" />
-               <eLabel text="Wireless Network Status..." position="90,50" size="600,32" font="Semiboldit;32" foregroundColor="#5d5d5d" backgroundColor="#27b5b9bd" transparent="1" />
-               <ePixmap pixmap="Vu_HD/icons/clock.png" position="750,55" zPosition="1" size="20,20" alphatest="blend" />
-               <widget source="global.CurrentTime" render="Label" position="770,57" zPosition="1" size="50,20" font="Regular;20" foregroundColor="#1c1c1c" backgroundColor="#27d9dee2" halign="right" transparent="1">
-                       <convert type="ClockToText">Format:%H:%M</convert>
-               </widget>
-               <ePixmap pixmap="Vu_HD/buttons/red.png" position="45,98" size="25,25" alphatest="blend" />
-               <widget source="key_red" render="Label" position="66,97" zPosition="1" size="150,25" font="Regular;20" halign="center" valign="center" backgroundColor="darkgrey" foregroundColor="#1c1c1c" transparent="1" />
-               <widget source="status" render="Label" position="110,200" size="650,400" transparent="1" font="Regular;22" foregroundColor="#1c1c1c" backgroundColor="#27d9dee2" zPosition="1" />
-       </screen>"""
+       skin =  """
+               <screen position="center,center" size="510,400" title="Wireless Network Status..." >
+                       <widget source="status" render="Label" position="5,15" size="500,350" font="Regular;18" zPosition="1" />
+
+                       <ePixmap pixmap="skin_default/buttons/red.png" position="185,360" size="140,40" alphatest="on" />
+                       <widget source="key_red" render="Label" position="185,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
+               </screen>
+               """
        def __init__(self, session,iface):
                Screen.__init__(self,session)
                self.session = session
-#              self.aplist = []
                self.iface = iface
                self["status"] = StaticText(_("Wait a moment..."))
                self["key_red"] = StaticText(_("Close"))
@@ -1235,6 +1543,7 @@ class Wlanstatus(Screen):
                        "red": self.close,
                }, -2)
                self.readstatus()
+               self.onClose.append(self.cleanup)
 
        def readstatus(self):
                self.wlanstatus = Console()
@@ -1254,7 +1563,6 @@ class Wlanstatus(Screen):
 
 
        def statusdisplay(self,data):
-               rlist = []              
                if data == 0:
                        self["status"].setText(_("No information..."))
                else:
@@ -1263,17 +1571,32 @@ class Wlanstatus(Screen):
        def ok(self):
                pass
 
+       def cleanup(self):
+               self.stopWlanStatusConsole()
+
+       def stopWlanStatusConsole(self):
+               if self.wlanstatus is not None:
+                       if len(self.wlanstatus.appContainers):
+                               for name in self.wlanstatus.appContainers.keys():
+                                       self.wlanstatus.kill(name)
+
 def openconfig(session, **kwargs):
-#      session.open(WlanSetup)
        session.open(WlanSelection)
 
 def selSetup(menuid, **kwargs):
+       list=[]
        if menuid != "system":
                return [ ]
-
-       return [(_("Wireless LAN Setup"), openconfig, "wlansetup_config", 80)]
+       else:
+               for x in iNetwork.getInstalledAdapters():
+                       if x.startswith('eth'):
+                               continue
+                       list.append(x)
+               if len(list):
+                       return [(_("Wireless LAN Setup"), openconfig, "wlansetup_config", 80)]
+               else:
+                       return [ ]
+       return [ ]
 
 def Plugins(**kwargs):
-       return  PluginDescriptor(name=_("Wireless LAN Setup"), description="Fan Control", where = PluginDescriptor.WHERE_MENU, fnc=selSetup);
-#      return [PluginDescriptor(name = "Fancontrols", description = "check Fan Control settings", where = PluginDescriptor.WHERE_AUTOSTART, fnc = setfancontrol),
-#      PluginDescriptor(name=_("Wireless LAN Setup"), description="Fan Control", where = PluginDescriptor.WHERE_MENU, fnc=selSetup)]
+       return  PluginDescriptor(name=_("Wireless LAN Setup"), description="Wireless LAN Setup", where = PluginDescriptor.WHERE_MENU, fnc=selSetup)