d0510bf743cebc24c5f01284c314398adc02fda2
[vuplus_dvbapp] / lib / python / Plugins / SystemPlugins / 3GModemManager / plugin.py
1 from Plugins.Plugin import PluginDescriptor
2
3 from Screens.Screen import Screen
4 from Screens.MessageBox import MessageBox
5 from Screens.DefaultWizard import DefaultWizard
6 from Screens.Standby import TryQuitMainloop
7 from Screens.VirtualKeyBoard import VirtualKeyBoard
8
9 from Components.Label import Label
10 from Components.Sources.StaticText import StaticText
11 from Components.ActionMap import NumberActionMap, ActionMap
12 from Components.Network import iNetwork
13 from Components.MenuList import MenuList
14 from Components.config import config, getConfigListEntry, ConfigInteger, ConfigSubsection, ConfigSelection, ConfigText, ConfigYesNo, NoSave, ConfigNothing
15 from Components.ConfigList import ConfigListScreen
16 from Components.Pixmap import Pixmap
17
18 from Tools.Directories import resolveFilename, SCOPE_PLUGINS, SCOPE_CURRENT_PLUGIN
19
20 from enigma import eTimer, eConsoleAppContainer, eSocketNotifier, getDesktop
21 from select import POLLIN, POLLPRI
22 from xml.sax import make_parser, handler
23 import os, socket, time
24
25 debug_mode_modem_mgr = False
26 def printDebugModemMgr(msg):
27         global debug_mode_modem_mgr
28         if debug_mode_modem_mgr:
29                 print "[ModemManager Plugin] Debug >>", msg
30
31 def printInfoModemMgr(msg):
32         print "[ModemManager Plugin] Info >>", msg
33
34 class DeviceEventListener:
35         notifyCallbackFunctionList = []
36         def __init__(self):
37                 self.sock = socket.socket(socket.AF_NETLINK, socket.SOCK_DGRAM, 15)
38                 try:            
39                         self.sock.bind((os.getpid(), 1))
40                         self.notifier = eSocketNotifier(self.sock.fileno(), POLLIN|POLLPRI)
41                         self.notifier.callback.append(self.cbEventHandler)
42                 except Exception, msg:
43                         print "[ModemManager Plugin] Error >>", msg
44                         self.sock.close()
45
46         def cbEventHandler(self, sockfd):
47                 recv = self.sock.recv(65536)
48                 #printDebugModemMgr(str(recv.splitlines()))
49                 if recv.startswith("add@/block") or recv.startswith("remove@/block"):
50                         for x in self.notifyCallbackFunctionList:
51                                 try:    x(recv)
52                                 except: self.notifyCallbackFunctionList.remove(x)
53
54         def addCallback(self, func):
55                 if func is not None:
56                         self.notifyCallbackFunctionList.append(func)
57
58         def delCallback(self, func):
59                 if func is not None:
60                         self.notifyCallbackFunctionList.remove(func)
61
62         def close(self):
63                 try:
64                         self.notifier.callback.remove(self.cbEventHandler)
65                         self.sock.close()
66                 except: pass
67
68 class TaskManager:
69         def __init__(self):
70                 self.taskIdx = 0
71                 self.taskList = []
72                 self.gTaskInstance = None
73                 self.occurError = False
74                 self.cbSetStatusCB = None
75
76         def append(self, command, cbDataFunc, cbCloseFunc):
77                 self.taskList.append([command+'\n', cbDataFunc, cbCloseFunc])
78
79         def dump(self):
80                 print "############### TASK ###############"
81                 print "Current Task Index :", self.taskIdx
82                 print "Current Task Instance :", self.gTaskInstance
83                 print "Occur Error :", self.occurError
84                 print "Task List:\n", self.taskList
85                 print "####################################"
86
87         def error(self):
88                 printInfoModemMgr("set task error!!")
89                 self.occurError = True
90
91         def reset(self):
92                 self.taskIdx = 0
93                 self.gTaskInstance = None
94                 self.occurError = False
95
96         def clean(self):
97                 self.reset()
98                 self.taskList = []
99                 self.cbSetStatusCB = None
100                 print "clear task!!"
101
102         def index(self):
103                 self.taskIdx
104
105         def setStatusCB(self, cbfunc):
106                 self.cbSetStatusCB = cbfunc
107                 
108         def next(self):
109                 if self.taskIdx >= len(self.taskList) or self.occurError:
110                         printInfoModemMgr("can't run task!!")
111                         return False
112                 command     = self.taskList[self.taskIdx][0]
113                 cbDataFunc  = self.taskList[self.taskIdx][1]
114                 cbCloseFunc = self.taskList[self.taskIdx][2]
115
116                 self.gTaskInstance = eConsoleAppContainer()
117                 if cbDataFunc is not None:
118                         self.gTaskInstance.dataAvail.append(cbDataFunc)
119                 if cbCloseFunc is not None:
120                         self.gTaskInstance.appClosed.append(cbCloseFunc)
121                 if self.cbSetStatusCB is not None:
122                         self.cbSetStatusCB(self.taskIdx)
123
124                 printInfoModemMgr("prepared command :%s"%(command))
125                 self.gTaskInstance.execute(command)
126                 self.taskIdx += 1
127                 return True
128
129 class ParserHandler(handler.ContentHandler):
130         nodeList = []
131         def startDocument(self):
132                 pass
133         def endDocument(self):  
134                 pass
135         def startElement(self, name, attrs):
136                 if name == 'apn':
137                         node = {}
138                         for attr in attrs.getNames():
139                                 node[attr] = attrs.getValue(attr)
140                         self.nodeList.append(node)
141         def endElement(self, name):
142                 pass
143         def characters(self, content):
144                 pass
145         def setDocumentLocator(self, locator):
146                 pass
147         def getNodeList(self):
148                 return self.nodeList
149
150 class EditModemManual(ConfigListScreen, Screen):
151         param = int(getDesktop(0).size().height()) >= 720 and (450,360) or (160,300)
152         skin =  """
153                 <screen position="center,center" size="600,360" title="3G Modem Manager Config Edit">
154                         <widget name="config" zPosition="2" position="0,0" size="600,300" scrollbarMode="showOnDemand" transparent="1" />
155
156                         <ePixmap pixmap="skin_default/buttons/red.png" position="5,320" size="140,40" alphatest="on" />
157                         <ePixmap pixmap="skin_default/buttons/green.png" position="155,320" size="140,40" alphatest="on" />
158                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="305,320" size="140,40" alphatest="on" />
159                         <ePixmap pixmap="skin_default/buttons/blue.png" position="455,320" size="140,40" alphatest="on" />
160
161                         <widget source="key_red" render="Label" position="5,320" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
162                         <widget source="key_green" render="Label" position="155,320" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />
163
164                         <widget name="VKeyIcon" pixmap="skin_default/buttons/key_text.png" position="50,200" zPosition="10" size="35,25" transparent="1" alphatest="on" />
165                         <widget name="HelpWindow" pixmap="skin_default/vkey_icon.png" position="%d,%d" zPosition="1" size="1,1" transparent="1" alphatest="on" />
166                 </screen>
167                 """ % param
168
169         def __init__(self, session, cbFuncClose, uid=None, pwd=None, pin=None, apn=None, phone='*99#'):
170                 Screen.__init__(self, session)
171                 self.cbFuncClose,self.uid,self.pwd,self.pin,self.apn,self.phone = cbFuncClose,uid,pwd,pin,apn,phone
172
173                 self["actions"] = ActionMap(["OkCancelActions", "ShortcutActions", "WizardActions", "ColorActions", "SetupActions",],
174                 {
175                         "ok":     self.keyOK,
176                         "cancel": self.keyExit,
177                         "red":    self.keyExit,
178                         "green":  self.keyOK,
179                 }, -2)
180
181                 self["VirtualKB"] = ActionMap(["VirtualKeyboardActions" ],
182                 {
183                         "showVirtualKeyboard": self.KeyText,
184                 }, -1)
185
186                 self.configList = []
187                 ConfigListScreen.__init__(self, self.configList, session=session)
188                 self.createConfigList()
189
190                 self["key_red"]    = StaticText(_("Cancel"))
191                 self["key_green"]  = StaticText(_("Save"))
192                 self["VKeyIcon"]   = Pixmap()
193                 self["HelpWindow"] = Pixmap()
194                 self["VirtualKB"].setEnabled(False)
195
196         def createConfigList(self):
197                 self.configUserName = ConfigText(default=str(self.uid), visible_width=50, fixed_size=False)
198                 self.configPassword = ConfigText(default=str(self.pwd), visible_width=50, fixed_size=False)
199                 self.configAPN      = ConfigText(default=str(self.apn), visible_width=50, fixed_size=False)
200                 self.configPIN      = ConfigText(default=str(self.pin), visible_width=50, fixed_size=False)
201                 self.configPhone    = ConfigText(default=str(self.phone), visible_width=50, fixed_size=False)
202
203                 self.configEntryUserName = getConfigListEntry(_("User :"),     self.configUserName)
204                 self.configEntryPassword = getConfigListEntry(_("Password :"), self.configPassword)
205                 self.configEntryAPN      = getConfigListEntry(_("APN :"),      self.configAPN)
206                 self.configEntryPIN      = getConfigListEntry(_("PIN :"),      self.configPIN)
207                 self.configEntryPhone    = getConfigListEntry(_("Phone :"),    self.configPhone)
208
209                 self.configList.append(self.configEntryUserName)
210                 self.configList.append(self.configEntryPassword)
211                 self.configList.append(self.configEntryAPN)
212                 self.configList.append(self.configEntryPIN)
213                 self.configList.append(self.configEntryPhone)
214
215                 self["config"].list = self.configList
216                 self["config"].l.setList(self.configList)
217
218         def getCurrentItem(self):
219                 currentPosition = self["config"].getCurrent()
220                 if currentPosition == self.configEntryUserName:
221                         return self.configUserName
222                 elif currentPosition == self.configEntryPassword:
223                         return self.configPassword
224                 elif currentPosition == self.configEntryAPN:
225                         return self.configAPN
226                 elif currentPosition == self.configEntryPIN:
227                         return self.configPIN
228                 elif currentPosition == self.configEntryPhone:
229                         return self.configPhone
230                 return None
231
232         def KeyText(self):
233                 currentItemValue = ""
234                 currentItem = self.getCurrentItem()
235                 if currentItem is None:
236                         currentItemValue = currentItem.value
237                 self.session.openWithCallback(self.cbKeyText, VirtualKeyBoard, title=("Please enter ap-info here"), text=currentItemValue)
238
239         def cbKeyText(self, data=None):
240                 if data is not None:
241                         currentItem = self.getCurrentItem()
242                         if currentItem is not None:
243                                 currentItem.setValue(data)
244
245         def keyExit(self):
246                 self.close()
247
248         def keyOK(self):
249                 if self.cbFuncClose is not None:
250                         self.uid = self.configUserName.value
251                         self.pwd = self.configPassword.value
252                         self.pin = self.configPIN.value
253                         self.apn = self.configAPN.value
254                         self.phone = self.configPhone.value
255                         self.cbFuncClose(self.uid,self.pwd,self.pin,self.apn,self.phone)
256                 self.close()
257
258
259 class ModemManual(Screen):
260         skin =  """
261                 <screen position="center,center" size="600,360" title="3G Modem Manager Config">
262                         <widget name="menulist" position="0,0" size="300,300" backgroundColor="#000000" zPosition="10" scrollbarMode="showOnDemand" />
263                         <widget name="apnInfo" position="310,0" size="290,300" font="Regular;20" halign="left" backgroundColor="#a08500" transparent="1" />
264
265                         <ePixmap pixmap="skin_default/buttons/red.png" position="5,320" size="140,40" alphatest="on" />
266                         <ePixmap pixmap="skin_default/buttons/green.png" position="155,320" size="140,40" alphatest="on" />
267                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="305,320" size="140,40" alphatest="on" />
268                         <ePixmap pixmap="skin_default/buttons/blue.png" position="455,320" size="140,40" alphatest="on" />
269
270                         <widget source="key_red" render="Label" position="5,320" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
271                         <widget source="key_green" render="Label" position="155,320" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />
272                         <widget source="key_yellow" render="Label" position="305,320" zPosition="1" size="140,40" font="Regular;20" valign="center" halign="center" backgroundColor="#a08500"  foregroundColor="#ffffff" transparent="1" />
273                 </screen>
274                 """
275
276         def __init__(self, session, cbFuncClose, uid=None, pwd=None, pin=None, apn=None, phone='*99#'):
277                 Screen.__init__(self, session)
278                 self.cbFuncClose,self.uid,self.pwd,self.pin,self.apn,self.phone = cbFuncClose,uid,pwd,pin,apn,phone
279                 self["actions"] = ActionMap(["OkCancelActions", "ShortcutActions", "WizardActions", "ColorActions", "SetupActions"],
280                 {
281                         "ok":     self.keyOK,
282                         "cancel": self.keyExit,
283                         "red":    self.keyExit,
284                         "green":  self.keyOK,
285                         "yellow": self.keyEdit,
286                         "left":   self.keyLeft,
287                         "right":  self.keyRight,
288                         "up":     self.keyUp,
289                         "down":   self.keyDown,
290                 }, -2)
291
292                 self.apnItems = self.setListOnView()
293                 self["menulist"]   = MenuList(self.apnItems)
294                 self["key_red"]    = StaticText(_("Cancel"))
295                 self["key_green"]  = StaticText(_("OK"))
296                 self["key_yellow"] = StaticText(_("Edit"))
297                 self["apnInfo"]    = Label(' ')
298
299                 self.updateAPNInfo()
300
301         def keyEdit(self):
302                 self.session.open(EditModemManual, self.cb3GManualSetting, self.uid,self.pwd,self.pin,self.apn,self.phone)
303
304         def cb3GManualSetting(self, uid=None, pwd=None, pin=None, apn=None, phone='*99#'):
305                 self.uid,self.pwd,self.pin,self.apn,self.phone = uid, pwd, pin, apn, phone
306                 self.updateAPNInfo()
307
308         def keyLeft(self):
309                 self['menulist'].pageUp()
310                 self.setAPNInfo()
311
312         def keyRight(self):
313                 self['menulist'].pageDown()
314                 self.setAPNInfo()
315
316         def keyUp(self):
317                 self['menulist'].up()
318                 self.setAPNInfo()
319
320         def keyDown(self):
321                 self['menulist'].down()
322                 self.setAPNInfo()
323
324         def keyOK(self):
325                 if self.cbFuncClose is not None:
326                         self.cbFuncClose(self.uid,self.pwd,self.pin,self.apn,self.phone)
327                 self.close()
328
329         def keyExit(self):
330                 self.close()
331
332         def setAPNInfo(self):
333                 try:
334                         x = self["menulist"].getCurrent()[1]
335                         self.apn, self.uid, self.pwd = x.get("apn"), x.get("user"), x.get("password")
336                 except Exception, err: 
337                         pass
338                 self.updateAPNInfo()
339
340         def updateAPNInfo(self):
341                 info = 'APN : %s\nUSER : %s\nPASSWD : %s\nPIN : %s\nPHONE : %s\n' % (str(self.apn), str(self.uid), str(self.pwd), str(self.pin), str(self.phone))
342                 self["apnInfo"].setText(info)
343
344         def setListOnView(self):
345                 lvApnItems = []
346                 def uppercaseCompare(a,b):
347                         aa = str(a.get("carrier"))
348                         bb = str(b.get("carrier"))
349                         return cmp(aa.upper(),bb.upper())
350                 def isExistAPN(name):
351                         for x in lvApnItems:
352                                 if x[0] == name:
353                                         return True
354                         return False
355                 try:
356                         handle = ParserHandler()
357                         parser = make_parser()
358                         parser.setContentHandler(handle)
359                         parser.parse(resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/3GModemManager/apnlist.xml"))
360
361                         apnList = handle.getNodeList()
362                         apnList.sort(uppercaseCompare)
363                         for x in apnList:
364                                 name = str(x.get('carrier'))
365                                 if name is None or name == 'None':
366                                         continue
367                                 if isExistAPN(name):
368                                         continue
369                                 d = {}
370                                 d['apn'] = str(x.get('apn'))
371                                 d['user'] = str(x.get('user'))
372                                 d['password'] = str(x.get('password'))
373                                 lvApnItems.append((name,d))
374                 except Exception, err: 
375                         print "ERROR >>", err
376                         pass
377                 return lvApnItems
378
379 class ModemManager(Screen):
380         skin =  """
381                 <screen position="center,center" size="600,360" title="3G Modem Manager">
382                         <widget name="menulist" position="0,0" size="300,150" backgroundColor="#000000" zPosition="10" scrollbarMode="showOnDemand" />
383                         <widget name="usbinfo" position="310,0" size="290,150" font="Regular;18" halign="left" />
384
385                         <widget name="statusTitle" position="0,160" size="600,120" font="Regular;20" halign="center" backgroundColor="#a08500" transparent="1" />
386                         <widget name="statusInfo" position="0,185" size="600,120" font="Regular;20" halign="left" backgroundColor="#a08500" transparent="1" />
387
388                         <ePixmap pixmap="skin_default/buttons/red.png" position="5,320" size="140,40" alphatest="on" />
389                         <ePixmap pixmap="skin_default/buttons/green.png" position="155,320" size="140,40" alphatest="on" />
390                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="305,320" size="140,40" alphatest="on" />
391                         <ePixmap pixmap="skin_default/buttons/blue.png" position="455,320" size="140,40" alphatest="on" />
392
393                         <widget source="key_red" render="Label" position="5,320" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
394                         <widget source="key_green" render="Label" position="155,320" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />
395                         <widget source="key_yellow" render="Label" position="305,320" zPosition="1" size="140,40" font="Regular;20" valign="center" halign="center" backgroundColor="#a08500"  foregroundColor="#ffffff" transparent="1" />
396                         <widget source="key_blue" render="Label" position="455,320" zPosition="1" size="140,40" font="Regular;20" valign="center" halign="center" backgroundColor="#18188b"  foregroundColor="#ffffff" transparent="1" />
397                 </screen>
398                 """
399         uid,pwd,pin,apn,phone = None,None,None,None,'*99#'
400         connectionStatus = 0
401         def __init__(self, session): 
402                 Screen.__init__(self, session)
403                 self.usb_lv_items = self.setListOnView()
404
405                 self["actions"] = ActionMap(["OkCancelActions", "ShortcutActions", "WizardActions", "ColorActions", "SetupActions", "NumberActions"],
406                 {
407                         "ok":     self.keyOK,
408                         "cancel": self.keyExit,
409                         "red":    self.keyExit,
410                         "green":  self.keyOK,
411                         "yellow": self.keyManual,
412                         "blue":   self.keyReset,
413                         "up":     self.keyUp,
414                         "down":   self.keyDown,
415                         "left":   self.keyLeft,
416                         "right":  self.keyRight,
417                         "0":      self.keyNumber,
418                 }, -2)
419                 self["menulist"] = MenuList(self.usb_lv_items)
420                 self['usbinfo'] = Label(' ')
421                 self['statusTitle'] = Label('[ Status ]')
422                 self['statusInfo'] = Label(' ')
423                 self["key_red"] = StaticText(_("Exit"))
424                 if self.isConnected():
425                         self["key_green"] = StaticText("Disconnect")
426                         self.setDisconnectStatus(0)
427                 else:
428                         self["key_green"] = StaticText("Connect")
429                         self.setConnectStatus(0)
430                 self["key_yellow"] = StaticText(_("Manual"))
431                 self["key_blue"] = StaticText(_("Reset"))
432
433                 self.updateUSBInfo()
434
435                 self.udevListener = DeviceEventListener()
436                 self.udevListener.addCallback(self.cbUdevListener)
437
438                 self.taskManager = TaskManager()
439
440                 self.refreshStatusTimer = eTimer()
441                 self.refreshStatusTimer.callback.append(self.cbRefreshStatus)
442
443                 #self.restartAppTimer = eTimer()
444                 #self.restartAppTimer.callback.append(self.cbRestartAppTimer)
445
446                 self.forceStop = False
447
448         def cbRestartAppTimer(self):
449                 self.restartAppTimer.stop()
450                 model = file('/proc/stb/info/vumodel').read().strip()
451                 if model is not None:
452                         if model == 'solo' or model == 'bm750':
453                                 self.session.open(TryQuitMainloop, 3)
454
455         def cbRefreshStatus(self):
456                 self.refreshStatusTimer.stop()
457                 if self["key_green"].getText() == 'Connect':
458                         self.setConnectStatus(0)
459                 elif self["key_green"].getText() == 'Disconnect': 
460                         self.setDisconnectStatus(0)
461
462         def cbUdevListener(self, data):
463                 printDebugModemMgr('Udev Listener Refresh!!')
464                 time.sleep(2)
465                 self["menulist"].setList(self.setListOnView())
466                 self.updateUSBInfo()
467
468         def isAttemptConnect(self):
469                 if self.connectionStatus == 0 or self.forceStop:
470                         return False
471                 maxIdx = 4
472                 if self["key_green"].getText() == 'Disconnect':
473                         maxIdx = 2
474                 if self.connectionStatus < maxIdx:
475                         printInfoModemMgr("can't excute a command during connecting...")
476                         return True
477                 return False
478
479         def keyManual(self):
480                 if self.isAttemptConnect():
481                         return
482                 self.session.open(ModemManual, self.cb3GManualSetting, self.uid,self.pwd,self.pin,self.apn,self.phone)
483
484         def keyReset(self):
485                 if self.isAttemptConnect():
486                         return
487                 self.cb3GManualSetting()
488
489         def cb3GManualSetting(self, uid=None, pwd=None, pin=None, apn=None, phone='*99#'):
490                 self.uid,self.pwd,self.pin,self.apn,self.phone = uid,pwd,pin,apn,phone
491                 self.updateUSBInfo()
492
493         def keyNumber(self, num=None):
494                 global debug_mode_modem_mgr
495                 debug_mode_modem_mgr = not debug_mode_modem_mgr
496                 printInfoModemMgr('changed log mode, debug %s'%(debug_mode_modem_mgr and 'on' or 'off'))
497
498         def keyExit(self):
499                 if self.isAttemptConnect():
500                         message = "Can't disconnect doring connecting.."
501                         self.session.open(MessageBox, _(message), MessageBox.TYPE_INFO)
502                         return
503                 self.udevListener.close()
504                 self.close()
505
506         def keyLeft(self):
507                 self["menulist"].pageUp()
508                 self.updateUSBInfo()
509
510         def keyRight(self):
511                 self["menulist"].pageDown()
512                 self.updateUSBInfo()
513
514         def keyUp(self):
515                 self["menulist"].up()
516                 self.updateUSBInfo()
517
518         def keyDown(self):
519                 self["menulist"].down()
520                 self.updateUSBInfo()
521
522         def keyOK(self):
523                 self.forceStop = False
524                 if self.isAttemptConnect():
525                         return
526
527                 def areadyExistAnotherAdapter():
528                         networkAdapters = iNetwork.getConfiguredAdapters()
529                         for x in networkAdapters:
530                                 if x[:3] != 'ppp':
531                                         return True
532                         return False
533
534                 if self["key_green"].getText() == 'Disconnect':
535                         message = "Do you want to disconnect?"
536                         self.session.openWithCallback(self.cbConfirmDone, MessageBox, _(message), default = False)
537                         return
538
539                 if areadyExistAnotherAdapter():
540                         message = "Another adapter connected has been found.\n\nA connection is attempted after disconnect all of other device. Do you want to?"
541                         self.session.openWithCallback(self.cbConfirmDone, MessageBox, _(message), default = True)
542                 else:   self.cbConfirmDone(True)
543
544         def cbConfirmDone(self, ret):
545                 if not ret: return
546                 if self["key_green"].getText() == 'Connect':
547                         networkAdapters = iNetwork.getConfiguredAdapters()
548                         for x in networkAdapters:
549                                 if x[:3] == 'ppp': continue
550                                 iNetwork.setAdapterAttribute(x, "up", False)
551                                 iNetwork.deactivateInterface(x)
552
553                 x = {}
554                 try: x = self["menulist"].getCurrent()[1]
555                 except:
556                         printInfoModemMgr('no selected device..')
557                         return
558
559                 devFile = '/usr/share/usb_modeswitch/%s:%s' % (x.get("Vendor"), x.get("ProdID"))
560                 if not os.path.exists(devFile) :
561                         message = "Can't found device file!! [%s]" % (devFile)
562                         printInfoModemMgr(message)
563                         self.session.open(MessageBox, _(message), MessageBox.TYPE_INFO)
564                         return
565
566                 #commandBin = resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/3GModemManager/3gcommand")
567                 commandBin = "/usr/bin/3gcommand"
568                 if self["key_green"].getText() == 'Disconnect':
569                         cmd = "%s -s 0" % (commandBin)
570                         self.taskManager.append(cmd, self.cbPrintAvail, self.cbPrintClose)
571
572                         cmd = "%s -s 1" % (commandBin)
573                         self.taskManager.append(cmd, self.cbPrintAvail, self.cbUnloadClose)
574                         self.taskManager.setStatusCB(self.setDisconnectStatus)
575                 else:
576                         cmd = "%s -s 2 -e vendor=0x%s -e product=0x%s" % (commandBin, x.get("Vendor"), x.get("ProdID"))
577                         self.taskManager.append(cmd, self.cbStep1PrintAvail, self.cbPrintClose)
578
579                         cmd = "%s -s 3 -e %s:%s" % (commandBin, x.get("Vendor"), x.get("ProdID"))
580                         self.taskManager.append(cmd, self.cbPrintAvail, self.cbPrintClose)
581
582                         cmd = "%s -s 4" % (commandBin)
583                         self.taskManager.append(cmd, self.cbStep3PrintAvail, self.cbMakeWvDialClose)
584
585                         cmd = "%s -s 5" % (commandBin)
586                         self.taskManager.append(cmd, self.cbRunWvDialAvail, self.cbPrintClose)
587                         self.taskManager.setStatusCB(self.setConnectStatus)
588                 
589                 self.taskManager.next()
590
591         def printStatus(self, idx, STATUS):
592                 message = ''
593                 self.connectionStatus = idx
594                 for x in range(0,len(STATUS)):
595                         if idx == x:
596                                 message += '  > '
597                         else:   message += '      '
598                         message += STATUS[x]
599                         message += '\n'
600                 self['statusInfo'].setText(message)
601
602         def setConnectStatus(self, idx):
603                 STATUS = {
604                  0:'1. Load a Mobile Broadband Device'
605                 ,1:'2. Set up a Mobile Broadband Device'
606                 ,2:'3. Generate a WvDial profile'
607                 ,3:'4. Attempt to connect'
608                 ,4:'5. Done'
609                 }
610                 self.printStatus(idx, STATUS)
611
612         def setDisconnectStatus(self, idx):
613                 STATUS = {
614                  0:'1. Drop WvDial'
615                 ,1:'2. Unload a Mobile Broadband Device'
616                 ,2:'3. Done'
617                 }
618                 self.printStatus(idx, STATUS)
619
620         def cbStep1PrintAvail(self, data):
621                 print data
622                 if data.find('modules.dep') > -1:
623                         self.forceStop = True
624
625         def cbStep3PrintAvail(self, data):
626                 print data
627                 if data.find('Sorry, no modem was detected') > -1:
628                         self.forceStop = True
629
630         def cbPrintAvail(self, data):
631                 print data
632
633         def cbPrintClose(self, ret):
634                 if self.forceStop:
635                         self.taskManager.clean()
636                         time.sleep(2)
637                         message = "Occur error during connection...\nPlease, check log!!"
638                         self.session.open(MessageBox, _(message), MessageBox.TYPE_INFO)
639                         return
640                 self.taskManager.next()
641
642         def cbUnloadClose(self, ret):
643                 self.taskManager.clean()
644                 time.sleep(2)
645                 self["key_green"].setText('Connect')
646                 self.setDisconnectStatus(2)
647                 self.refreshStatusTimer.start(1000)
648
649         def cbRunWvDialAvail(self, data):
650                 print data
651                 if data.find('Pid of pppd:') > -1:
652                         self.taskManager.clean()
653                         time.sleep(2)
654                         self["key_green"].setText('Disconnect')
655                         self.setConnectStatus(4)
656                         self.refreshStatusTimer.start(1000)
657                         #self.restartAppTimer.start(3000)
658
659         def cbMakeWvDialClose(self, ret):
660                 info = {}
661                 try:
662         
663                         datalist = file('/etc/wvdial.conf').read().splitlines()
664                         for x in datalist:
665                                 if x.startswith('Modem ='):
666                                         print x
667                                         info['Modem'] = x[7:].strip()
668                                 elif x.startswith('Init2 ='):
669                                         print x
670                                         info['Init'] = x[7:].strip()
671                                 elif x.startswith('Baud ='):
672                                         print x
673                                         info['Baud'] = x[6:].strip()
674                 except Exception, err: 
675                         printDebugModemMgr("getModemInfo Error : [%s]" % (str(err)))
676                         # TODO : occur error!!
677                         return
678
679                 if self.apn is not None:
680                         info['apn'] = self.apn
681                 if self.uid is not None:
682                         info['uid'] = self.uid
683                 if self.pwd is not None:
684                         info['pwd'] = self.pwd
685                 if self.pin is not None:
686                         info['pin'] = self.pin
687                 if self.phone is not None:
688                         info['phone'] = self.phone
689                 #info['phone'] = '*99#'
690                 self.makeWvDialConf(info)
691                 self.taskManager.next()
692
693         def writeConf(self, data, oper='>>'):
694                 confFile = '/etc/wvdial.conf'
695                 if oper == '>':
696                         os.system('mv %s %s.bak' % (confFile, confFile))
697                 cmd = "echo '%s' %s %s" % (data, oper, confFile)
698                 os.system(cmd)
699
700         def makeWvDialConf(self, params):
701                 baud  = params.get('Baud')
702                 init  = params.get('Init')
703                 modem = params.get('Modem')
704                 phone = params.get('phone')
705                 apn = params.get('apn')
706                 uid = params.get('uid')
707                 pwd = params.get('pwd')
708                 pin = params.get('pin')
709                 idxInit = 1
710
711                 self.writeConf('','>')
712
713                 self.writeConf('[Dialer Defaults]')
714                 if modem is None or init is None or baud is None:
715                         return False
716                 self.writeConf('Modem = %s' % (modem))
717                 self.writeConf('Baud = %s' % (baud))
718                 self.writeConf('Dial Command = ATDT')
719                 self.writeConf('Init%d = ATZ' % (idxInit))
720                 idxInit = idxInit + 1
721                 if pin is not None:
722                         writeConf('Init%d = AT+CPIN=%s' % (init_idx, pin))
723                         idxInit = idxInit + 1
724                 self.writeConf('Init%d = %s' % (idxInit, init))
725                 idxInit = idxInit + 1
726                 if apn is None and uid is None and pwd is None and pin is None:
727                         self.writeConf('Init%d = AT&F' % (idxInit))
728                         idxInit = idxInit + 1
729                 if apn is not None:
730                         self.writeConf('Init%d = AT+CGDCONT=1,"IP","%s"' % (idxInit, apn))
731                         idxInit = idxInit + 1
732                 self.writeConf('Init%d = AT+CFUN = 1' % (idxInit))
733                 self.writeConf('Username = %s' % (uid))
734                 self.writeConf('Password = %s' % (pwd))
735                 self.writeConf('Phone = %s' % (phone)) #*99#
736                 self.writeConf('Modem Type = Analog Modem')
737                 self.writeConf('ISDN = 0')
738                 self.writeConf('Carrier Check = 0')
739                 self.writeConf('Abort on No Dialtone = 0')
740                 self.writeConf('Stupid Mode = 1')
741                 self.writeConf('Check DNS = 1')
742                 self.writeConf('Check Def Route = 1')
743                 self.writeConf('Auto DNS = 1')
744
745         def isConnected(self):
746                 return len(os.popen('ifconfig -a | grep ppp').read().strip()) > 0
747
748         def updateUSBInfo(self):
749                 info = ' '
750                 try:
751                         x = self["menulist"].getCurrent()[1]
752                         info = 'Vendor : %s/%s\nAPN : %s\nUser : %s\nPassword : %s\nPin : %s\nPhone : %s' % (
753                                         x.get("Vendor"), 
754                                         x.get("ProdID"), 
755                                         str(self.apn),
756                                         str(self.uid),
757                                         str(self.pwd),
758                                         str(self.pin),
759                                         str(self.phone)
760                                 )
761                 except: pass
762                 self['usbinfo'].setText(info)
763
764         def setListOnView(self):
765                 lv_usb_items = []
766                 try:
767                         for x in self.getUSBList():
768                                 lv_usb_items.append((x.get("Product"),x))
769                 except: pass
770                 return lv_usb_items
771
772         def getUSBList(self):
773                 parsed_usb_list = []
774                 usb_devices = os.popen('cat /proc/bus/usb/devices').read()
775                 tmp_device = {}
776                 for x in usb_devices.splitlines():
777                         if x is None or len(x) == 0:
778                                 printDebugModemMgr("TMP DEVICE : [%s]" % (tmp_device))
779                                 if len(tmp_device):
780                                         parsed_usb_list.append(tmp_device)
781                                 tmp_device = {}
782                                 continue
783                         try:
784                                 if x[0] in ('P', 'S', 'I', 'T'):
785                                         tmp = x[2:].strip()
786                                         printDebugModemMgr("TMP : [%s]" % (tmp))
787                                         if tmp.startswith('Bus='):
788                                                 #printDebugModemMgr("TMP SPLIT for BUS : [%s]" % (str(tmp.split())))
789                                                 for xx in tmp.split():
790                                                         if xx.startswith('Bus='):
791                                                                 tmp_device['Bus'] = xx[4:]
792                                                                 break
793                                         if tmp.startswith('Manufacturer='):
794                                                 tmp_device['Manufacturer'] = tmp[13:]
795                                         if tmp.startswith('Product='):
796                                                 tmp_device['Product'] = tmp[8:]
797                                         elif tmp.startswith('SerialNumber='):
798                                                 tmp_device['SerialNumber'] = tmp[13:]
799                                         elif tmp.startswith('Vendor='):
800                                                 #printDebugModemMgr("TMP SPLIT for BUS : [%s]" % (str(tmp.split())))
801                                                 for xx in tmp.split():
802                                                         if xx.startswith('Vendor='):
803                                                                 tmp_device['Vendor'] = xx[7:]
804                                                         elif xx.startswith('ProdID='):
805                                                                 tmp_device['ProdID'] = xx[7:]
806                                                 #tmp_device['Vendor'] = tmp
807                                         elif tmp.find('Driver=') > 0:
808                                                 d = tmp[tmp.find('Driver=')+7:]
809                                                 if d != '(none)':
810                                                         tmp_device['Interface'] = d
811                         except Exception, errmsg:
812                                 print errmsg
813                 if len(tmp_device):
814                         parsed_usb_list.append(tmp_device)
815                 printDebugModemMgr("PARSED DEVICE LIST : " + str(parsed_usb_list))
816                 rt_usb_list = []
817                 for x in parsed_usb_list:
818                         printDebugModemMgr('Looking >> ' + str(x))
819                         try:
820                                 xx = x.get("Interface")
821                                 if xx.startswith('usb'):
822                                         rt_usb_list.append(x)
823                         except: pass
824                 printInfoModemMgr("USB DEVICE LIST : " + str(rt_usb_list))
825                 return rt_usb_list
826
827 def main(session, **kwargs):
828         session.open(ModemManager)
829                                                            
830 def Plugins(**kwargs):            
831         return PluginDescriptor(name=_("Modem Manager"), description="management 3g modem", where = PluginDescriptor.WHERE_PLUGINMENU, fnc=main)
832