示例#1
0
def generate_phone_features():
    r={}
    for model in phones.phonemodels:
        module=common.importas(phones.module(model))
        # check for Profile._supportedsyncs
        support_sync=[(x[0], x[1]) for x in module.Profile._supportedsyncs]
        d={}
        for f in features:
            d[f]={ 'r': False, 'w': False }
            if (f, 'read') in support_sync:
                if hasattr(module.Phone, req_attrs[f]['r']) and\
                   getattr(module.Phone, req_attrs[f]['r']) is not NotImplemented\
                   and getattr(module.Phone, req_attrs[f]['r']) is not None:
                    d[f]['r']=True
            if (f, 'write') in support_sync:
                if hasattr(module.Phone, req_attrs[f]['w']) and\
                   getattr(module.Phone, req_attrs[f]['w']) is not NotImplemented\
                   and getattr(module.Phone, req_attrs[f]['w']) is not None:
                    d[f]['w']=True
        for f in misc_features:
            d[f]={ 'x': req_attrs[f](module) }
        if hasattr(module.Phone, 'helpid') and module.Phone.helpid:
            _model_name='<a href="%s">%s</a>'%( module.Phone.helpid, model)
        else:
            _model_name=model
        r[_model_name]=d
    return r
 def detect(self, using_port=None):
     coms=comscan.comscan()
     self.log('coms:'+str(coms))
     available_modem_coms=[x['name'] for x in coms if x['available'] \
                           and x['class']=='modem']
     if using_port is None:
         available_coms=[x['name'] for x in coms if x['available']]
     else:
         available_coms=[using_port]
         available_modem_coms=[x for x in available_coms if x in available_modem_coms]
     self.log('Available ports: '+str(available_coms))
     self.log('Available modem ports: '+str(available_modem_coms))
     self.__q_on=True
     threads=[threading.Thread(target=self.do_get_data, args=(e,)) \
              for e in available_modem_coms]
     for t in threads:
         t.start()
     for t in threads:
         t.join()
     self.__q_on=False
     while not self.__q_log.empty():
         q=self.__q_log.get_nowait()
         if isinstance(q, (list, tuple)):
             self.logdata(*q)
         else:
             self.log(q)
     pm=phones.phonemodels
     models=pm.keys()
     models.sort()
     found_port=found_model=None
     for model in models:
         self.log('Checking for model: '+model)
         module=common.importas(pm[model])
         if hasattr(module.Phone, 'detectphone'):
             likely_ports=[x['name'] for x in coms if \
                           x['available'] and \
                           comdiagnose.islikelyport(x, module)]
             self.log('Likely ports:'+str(likely_ports))
             found_port=getattr(module.Phone, 'detectphone')(coms,
                                                             likely_ports,
                                                             self.__data,
                                                             module,
                                                             self)
             self.log('Detect Phone result: '+`self.__data`)
             if found_port is not None:
                 self.log('Phone '+model+' returned port:'+`found_port`)
                 found_model=model
                 break
         found_port=self.__check_profile(module.Profile)
         if found_port is not None:
             found_model=model
             break
     if found_port is None:
         found_port, found_model=self.__check_for_other_cdma()
     if found_port is not None and found_model is not None:
         self.log('Found phone:'+found_model+' port:'+`found_port`)
         return { 'port': found_port, 'phone_name': found_model,
                  'phone_module': pm[found_model],
                  'phone_esn': self.__data[found_port]['esn'] }
 def set(self, data):
     self._model_name=data.get('phone', '')
     self._model.SetLabel(self._model_name)
     self._com_port=data.get('com', '')
     self._port.SetLabel(self._com_port)
     _module=common.importas(phones.module(self._model_name))
     self._det_btn.Enable(bool(self._model_name and \
                               hasattr(_module.Phone,
                                      'detectphone'))) 
示例#4
0
 def __init__(self,
              arg,
              file_in,
              file_out,
              file_err,
              config_filename=None,
              comm_port=None,
              phone_model=None):
     """Constructor
     @param arg: command string including the command and its argument
     @param file_in: input stream file object
     @param file_out: output stream file object
     @param file_err: error strean file object
     @param config_filename: use this config file instead of the default
     @param comm_port: string name of the comm port to use (default to config file)
     @param phone_model: string phone model to use (default to config file)
     """
     self.OK = False
     self._inCLI = False
     try:
         _cmd_line = arg.split(None)
         self.cmd = _cmd_line[0]
         self.args = _cmd_line[1:]
         self.config = bp_config.Config(config_filename)
         _commport = comm_port if comm_port else self.config.Read(
             "lgvx4400port", None)
         _phonemodel = phone_model if phone_model else self.config.Read(
             "phonetype", None)
         if os.environ.get('PHONE_FS', None):
             # running in BREW FS debug/sim mode
             self.commport = None
         else:
             self.commport = commport.CommConnection(self, _commport)
         try:
             self.phonemodule = common.importas(phones.module(_phonemodel))
         except KeyError:
             raise PhoneModelError
         self.phone = self.phonemodule.Phone(self, self.commport)
         self._rootdir = ''
         self._pwd = self._rootdir
         self._in = file_in
         self._out = file_out
         self._err = file_err
         # initialize the Brew file cache
         com_brew.file_cache = com_brew.FileCache(
             self.config.Read('path', ''))
     except common.CommsOpenFailure:
         file_err.write('Error: Failed to open comm port %s\n' % _commport)
     except PhoneModelError:
         file_err.write('Error: Phone Model %s not available\n' %
                        _phonemodel)
     else:
         self.OK = True
示例#5
0
 def set(self, data):
     self._status.SetLabel('')
     self._model_name = data.get('phone', '')
     self._model.SetLabel(self._model_name)
     self._com_port = data.get('com', '')
     self._port.SetLabel(self._com_port)
     _module = common.importas(phones.module(self._model_name))
     self._det_btn.Enable(bool(self._model_name and \
                               (hasattr(_module.Phone,
                                        'detectphone') or \
                                hasattr(_module.Profile,
                                        'phone_model'))))
示例#6
0
def generate_udevrules():
    """Generate the udev rules file based on all the known VIDs and PIDs"""
    global udevrules_filename, udevrules_line
    _ids={}
    for _f in phones.getallmodulenames():
        _profile=importas(_f)
        if hasattr(_profile.Profile, 'usbids'):
            for _id in _profile.Profile.usbids:
                _ids[_id]=True
    _rules=[]
    for _entry in _ids:
        _rules.append(udevrules_line%(_entry[1], _entry[0]))
    _f=file('resources/%s'%udevrules_filename, 'wt').write('\n'.join(_rules))
 def OnImportModule(self, _):
     dlg=wx.TextEntryDialog(self, 'Enter the name of a Python Module:',
                            'Module Import')
     if dlg.ShowModal()==wx.ID_OK:
         try:
             self._module=common.importas(dlg.GetValue())
         except ImportError:
             self._module=None
             w=wx.MessageDialog(self, 'Failed to import module: '+dlg.GetValue(),
                              'Module Import Error',
                              style=wx.OK|wx.ICON_ERROR)
             w.ShowModal()
             w.Destroy()
     dlg.Destroy()
示例#8
0
 def OnImportModule(self, _):
     with guihelper.WXDialogWrapper(
         wx.TextEntryDialog(self, "Enter the name of a Python Module:", "Module Import"), True
     ) as (dlg, retcode):
         if retcode == wx.ID_OK:
             try:
                 self._module = common.importas(dlg.GetValue())
             except ImportError:
                 self._module = None
                 guihelper.MessageDialog(
                     self,
                     "Failed to import module: " + dlg.GetValue(),
                     "Module Import Error",
                     style=wx.OK | wx.ICON_ERROR,
                 )
示例#9
0
 def __init__(self, arg, file_in, file_out, file_err,
              config_filename=None, comm_port=None,
              phone_model=None):
     """Constructor
     @param arg: command string including the command and its argument
     @param file_in: input stream file object
     @param file_out: output stream file object
     @param file_err: error strean file object
     @param config_filename: use this config file instead of the default
     @param comm_port: string name of the comm port to use (default to config file)
     @param phone_model: string phone model to use (default to config file)
     """
     self.OK=False
     self._inCLI=False
     try:
         _cmd_line=arg.split(None)
         self.cmd=_cmd_line[0]
         self.args=_cmd_line[1:]
         self.config=bp_config.Config(config_filename)
         _commport=comm_port if comm_port else self.config.Read("lgvx4400port", None)
         _phonemodel=phone_model if phone_model else self.config.Read("phonetype", None)
         if os.environ.get('PHONE_FS', None):
             # running in BREW FS debug/sim mode
             self.commport=None
         else:
             self.commport=commport.CommConnection(self, _commport)
         try:
             self.phonemodule=common.importas(phones.module(_phonemodel))
         except KeyError:
             raise PhoneModelError
         self.phone=self.phonemodule.Phone(self, self.commport)
         self._rootdir=''
         self._pwd=self._rootdir
         self._in=file_in
         self._out=file_out
         self._err=file_err
         # initialize the Brew file cache
         com_brew.file_cache=com_brew.FileCache(self.config.Read('path', ''))
     except common.CommsOpenFailure:
         file_err.write('Error: Failed to open comm port %s\n'%_commport)
     except PhoneModelError:
         file_err.write('Error: Phone Model %s not available\n'%_phonemodel)
     else:
         self.OK=True
                   port['usb-interface#']==iface:
                return score
        if port.has_key('hardwareinstance'):
            v=port['hardwareinstance'].lower()
            str="vid_%04x&pid_%04x" % (vid,pid)
            if v.find(str)>=0:
                return score
    score+=10
    if port.has_key("libusb"):
        return -1
    if port.has_key("hardwareinstance") and \
       re.search("vid_([0-9a-f]){4}&pid_([0-9a-f]){4}", port['hardwareinstance'], re.I) is not None:
        return -1
    if sys.platform!='win32' and ( \
        port['name'].lower().find('usb')>0 or port.get("driver","").lower().find('usb')>=0):
        return score
    if sys.platform=='win32' and (getattr(phonemodule.Profile, 'bluetooth_mfg_id', 0) != 0) and \
        port['hardwareinstance'].find('BTHENUM\\')==0 and \
        port['hardwareinstance'].find(getattr(phonemodule.Profile, 'bluetooth_mfg_id', 'XXX'))>0:
        return score
    return -1
def autoguessports(phonemodule):
    """Returns a list of ports (most likely first) for finding the phone on"""
    res=[]
    ports=[(islikelyportscore(port, phonemodule), port) for port in comscan.comscan()+usbscan.usbscan()+bitflingscan.flinger.scan() if port['available']]
    ports.sort()
    return [ (port['name'], port) for score,port in ports if score>=0]
if __name__=='__main__':
    import common
    print autoguessports(common.importas("phones.com_lgvx4400"))
	def OnImportModule(self, _):

        dlg=wx.TextEntryDialog(self, 'Enter the name of a Python Module:',
                               'Module Import')

        if dlg.ShowModal()==wx.ID_OK:

            try:

                self._module=common.importas(dlg.GetValue())

            except ImportError:

                self._module=None

                w=wx.MessageDialog(self, 'Failed to import module: '+dlg.GetValue(),
                                 'Module Import Error',
                                 style=wx.OK|wx.ICON_ERROR)

                w.ShowModal()

                w.Destroy()

        dlg.Destroy()

	def OnStartSelMenu(self, evt):

        ofs=self.current_ofs

        if ofs is not None:

            self.highlightstart=ofs

            self.needsupdate=True

            self.Refresh()

        self.set_sel(self.highlightstart, self.highlightend)

	def OnEndSelMenu(self, _):

        ofs=self.current_ofs

        if ofs is not None:

            self.highlightend=ofs+1

            self.needsupdate=True

            self.Refresh()

        self.set_sel(self.highlightstart, self.highlightend)

	def OnViewValue(self, _):

        ofs=self.current_ofs

        if ofs is not None:

            self._display_result(self._gen_values(self.data, ofs))

	def OnStartSelection(self, evt):

        self.highlightstart=self.highlightend=None

        ofs=self._set_and_move(evt)

        if ofs is not None:

            self.highlightstart=ofs

            self.dragging=True

            self.set_val(self.data[ofs:])

        else:

            self.set_val(None)

        self.needsupdate=True

        self.Refresh()

        self.set_pos(ofs)

        self.set_sel(self.highlightstart, self.highlightend)

	def OnMakeSelection(self, evt):

        if not self.dragging:

            return

        ofs=self._set_and_move(evt)

        if ofs is not None:

            self.highlightend=ofs+1

            self.needsupdate=True

            self.Refresh()

        self.set_pos(ofs)

        self.set_sel(self.highlightstart, self.highlightend)

	def OnEndSelection(self, evt):

        self.dragging=False

        ofs=self._set_and_move(evt)

        self.set_pos(ofs)

        self.set_sel(self.highlightstart, self.highlightend)

	def OnRightClick(self, evt):

        self.current_ofs=self._set_and_move(evt)

        if self.current_ofs is None:

            self.set_val(None)

        else:

            self.set_val(self.data[self.current_ofs:])

        self.set_pos(self.current_ofs)

        self._bgmenu.Enable(self._apply_menu_id, self._module is not None)

        self._bgmenu.Enable(self._reload_menu_id, self._module is not None)

        self.PopupMenu(self._bgmenu, evt.GetPosition())

	def OnTemplateLoad(self, _):

        dlg=wx.FileDialog(self, 'Select a file to load',
                          wildcard='*.tmpl',
                          style=wx.OPEN|wx.FILE_MUST_EXIST)

        if dlg.ShowModal()==wx.ID_OK:

            result={}

            try:

                execfile(dlg.GetPath())

            except UnicodeError:

                common.unicode_execfile(dlg.GetPath())

            exist_keys={}

            for i,e in enumerate(self._templates):

                exist_keys[e.name]=i

            for d in result['templates']:

                data_struct=DataStruct('new struct')

                data_struct.set(d)

                if exist_keys.has_key(data_struct.name):

                    self._templates[exist_keys[data_struct.name]]=data_struct

                else:

                    self._templates.append(data_struct)

        dlg.Destroy()

	def OnTemplateSaveAs(self, _):

        dlg=wx.FileDialog(self, 'Select a file to save',
                          wildcard='*.tmpl',
                          style=wx.SAVE|wx.OVERWRITE_PROMPT)

        if dlg.ShowModal()==wx.ID_OK:

            r=[x.get() for x in self._templates]

            common.writeversionindexfile(dlg.GetPath(),
                                         { 'templates': r }, 1)

        dlg.Destroy()

	def OnTemplateApply(self, _):

        if not self._templates:

            return

        choices=[x.name for x in self._templates]

        dlg=wx.SingleChoiceDialog(self, 'Select a template to apply:',
                            'Apply Data Template',
                            choices)

        if dlg.ShowModal()==wx.ID_OK:

            try:

                res=self._apply_template(dlg.GetStringSelection())

                self._display_result(res)

            except:

                raise

                w=wx.MessageDialog(self, 'Apply Template raised an exception',
                                   'Apply Template Error',
                                   style=wx.OK|wx.ICON_ERROR)

                w.ShowModal()

                w.Destroy()

        dlg.Destroy()

	def OnTemplateEdit(self, _):

        dlg=TemplateDialog(self)

        dlg.set(self._templates)

        if dlg.ShowModal()==wx.ID_OK:

            self._templates=dlg.get()

        dlg.Destroy()

	def OnSearch(self, evt):

        dlg=wx.TextEntryDialog(self, 'Enter data to search (1 0x23 045 ...):',
                               'Search Data')

        if dlg.ShowModal()==wx.ID_OK:

            l=dlg.GetValue().split(' ')

            s=''

            for e in l:

                if e[0:2]=='0x':

                    s+=chr(int(e, 16))

                elif e[0]=='0':

                    s+=chr(int(e, 8))

                else:

                    s+=chr(int(e))

            i=self.data[self.current_ofs:].find(s)

            if i!=-1:

                self._search_string=s

                self.highlightstart=i+self.current_ofs

                self.highlightend=self.highlightstart+len(s)

                self.needsupdate=True

                self.Refresh()

                self.set_sel(self.highlightstart, self.highlightend)

            else:

                self._search_string=None

	def OnSearchAgain(self, evt):

        if self._search_string is not None:

            i=self.data[self.current_ofs:].find(self._search_string)

            if i==-1:

                return

            self.highlightstart=i+self.current_ofs

            self.highlightend=self.highlightstart+len(self._search_string)

            self.needsupdate=True

            self.Refresh()

            self.set_sel(self.highlightstart, self.highlightend)

	def OnSize(self, evt):

        if evt is None:

            self.width=(self.widthinchars+3)*self.charwidth

            self.height=self.charheight*20

            self.SetClientSize((self.width, self.height))

            self.SetCaret(wx.Caret(self, (self.charwidth, self.charheight)))

            self.GetCaret().Show(True)

        else:

            self.width,self.height=self.GetClientSizeTuple()

        self.needsupdate=True

	def OnGainFocus(self,_):

        self.hasfocus=True

        self.needsupdate=True

        self.Refresh()

	def OnLoseFocus(self,_):

        self.hasfocus=False

        self.needsupdate=True

        self.Refresh()

	def highlightrange(self, start, end):

        self.needsupdate=True

        self.highlightstart=start

        self.highlightend=end

        self.Refresh()

        self.set_pos(None)

        self.set_sel(self.highlightstart, self.highlightend)

        self.set_val(None)

	def _ishighlighted(self, pos):

        return pos>=self.highlightstart and pos<self.highlightend

	def sethighlight(self, foreground, background):

        self.highlight=foreground,background

	def setnormal(self, foreground, background):

        self.normal=foreground,background

	def setfont(self, font):

        dc=wx.ClientDC(self)

        dc.SetFont(font)

        self.charwidth, self.charheight=dc.GetTextExtent("M")

        self.font=font

        self.updatescrollbars()

	def updatescrollbars(self):

        lines=len(self.data)/16

        if lines==0 or len(self.data)%16:

            lines+=1

        self.datalines=lines

        self.widthinchars=8+2+3*16+1+2+16

        self.SetScrollbars(self.charwidth, self.charheight, self.widthinchars, lines, self.GetViewStart()[0], self.GetViewStart()[1])

	def _setnormal(self,dc):

        dc.SetTextForeground(self.normal[0])

        dc.SetTextBackground(self.normal[1])

	def _sethighlight(self,dc):

        dc.SetTextForeground(self.highlight[0])

        dc.SetTextBackground(self.highlight[1])

	def _setstatus(self,dc):

        dc.SetTextForeground(self.normal[1])

        dc.SetTextBackground(self.normal[0])

        dc.SetBrush(wx.BLACK_BRUSH)

	def OnDraw(self, dc):

        xd,yd=self.GetViewStart()

        st=0  

        dc.BeginDrawing()

        dc.SetBackgroundMode(wx.SOLID)

        dc.SetFont(self.font)

        for line in range(yd, min(self.datalines, yd+self.height/self.charheight+1)):

            self._setnormal(dc)

            st=0

            dc.DrawText("%08X" % (line*16), 0, line*self.charheight)

            for i in range(16):

                pos=line*16+i

                if pos>=len(self.data):

                    break

                hl=self._ishighlighted(pos)

                if hl!=st:

                    if hl:

                        st=1

                        self._sethighlight(dc)

                    else:

                        st=0

                        self._setnormal(dc)

                if hl:

                    space=""

                    if i<15:

                        if self._ishighlighted(pos+1):

                            space=" "

                            if i==7:

                                space="  "

                else:

                    space=""

                c=self.data[pos]

                dc.DrawText("%02X%s" % (ord(c),space), (10+(3*i)+(i>=8))*self.charwidth, line*self.charheight)

                if not (ord(c)>=32 and string.printable.find(c)>=0):

                    c='.'

                dc.DrawText(c, (10+(3*16)+2+i)*self.charwidth, line*self.charheight)

        dc.EndDrawing()

	def updatebuffer(self):

        if self.buffer is None or \
           self.buffer.GetWidth()!=self.width or \
           self.buffer.GetHeight()!=self.height:

            if self.buffer is not None:

                del self.buffer

            self.buffer=wx.EmptyBitmap(self.width, self.height)

        mdc=wx.MemoryDC()

        mdc.SelectObject(self.buffer)

        mdc.SetBackground(wx.TheBrushList.FindOrCreateBrush(self.GetBackgroundColour(), wx.SOLID))

        mdc.Clear()

        self.PrepareDC(mdc)

        self.OnDraw(mdc)

        mdc.SelectObject(wx.NullBitmap)

        del mdc

	def OnPaint(self, event):

        if self.needsupdate:

            self.needsupdate=False

            self.updatebuffer()

        dc=wx.PaintDC(self)

        dc.BeginDrawing()

        dc.DrawBitmap(self.buffer, 0, 0, False)

        dc.EndDrawing()

	def OnScrollWin(self, event):

        self.needsupdate=True

        self.Refresh() 

        event.Skip()


class  HexEditorDialog (wx.Dialog) :
	_pane_widths=[-2, -3, -4]
	    _pos_pane_index=0
	    _sel_pane_index=1
	    _val_pane_index=2
	    def __init__(self, parent, data='', title='BitPim Hex Editor', helpd_id=-1):

        super(HexEditorDialog, self).__init__(parent, -1, title,
                                              size=(500, 500),
                                              style=wx.DEFAULT_DIALOG_STYLE|\
                                              wx.RESIZE_BORDER)

        self._status_bar=wx.StatusBar(self, -1)

        self._status_bar.SetFieldsCount(len(self._pane_widths))

        self._status_bar.SetStatusWidths(self._pane_widths)

        vbs=wx.BoxSizer(wx.VERTICAL)

        self._hex_editor=HexEditor(self, _set_pos=self.set_pos,
                                   _set_val=self.set_val,
                                   _set_sel=self.set_sel)

        self._hex_editor.SetData(data)

        self._hex_editor.SetTitle(title)

        vbs.Add(self._hex_editor, 1, wx.EXPAND|wx.ALL, 5)

        vbs.Add(wx.StaticLine(self), 0, wx.EXPAND|wx.ALL, 5)

        ok_btn=wx.Button(self, wx.ID_OK, 'OK')

        vbs.Add(ok_btn, 0, wx.ALIGN_CENTRE|wx.ALL, 5)

        vbs.Add(self._status_bar, 0, wx.EXPAND|wx.ALL, 0)

        self.SetSizer(vbs)

        self.SetAutoLayout(True)

        vbs.Fit(self)

	def set_pos(self, pos):

        """Display the current buffer offset in the format of
        Pos: 0x12=18
        """

        if pos is None:

            s=''

        else:

            s='Pos: 0x%X=%d'%(pos, pos)

        self._status_bar.SetStatusText(s, self._pos_pane_index)

	def set_sel(self, sel_start, sel_end):

        if sel_start is None or sel_start==-1 or\
           sel_end is None or sel_end ==-1:

            s=''

        else:

            sel_len=sel_end-sel_start

            sel_end-=1

            s='Sel: 0x%X=%d to 0x%X=%d (0x%X=%d bytes)'%(
                sel_start, sel_start, sel_end, sel_end,
                sel_len, sel_len)

        self._status_bar.SetStatusText(s, self._sel_pane_index)

	def set_val(self, v):

        if v:

            s='Val: 0x%02X=%d'%(ord(v[0]), ord(v[0]))

            if len(v)>1:

                u_s=struct.unpack('<H', v[:struct.calcsize('<H')])[0]

                s+=' 0x%04X=%d'%(u_s,  u_s)

            if len(v)>3:

                u_i=struct.unpack('<I', v[:struct.calcsize('<I')])[0]

                s+=' 0x%08X=%d'%(u_i, u_i)

        else:

            s=''

        self._status_bar.SetStatusText(s, self._val_pane_index)

	def set(self, data):

        self._hex_editor.SetData(data)


if __name__=='__main__':

    import sys

    if len(sys.argv)!=2:

        print 'Usage:',sys.argv[0],'<File Name>'

        sys.exit(1)

    app=wx.PySimpleApp()

    dlg=HexEditorDialog(None, file(sys.argv[1], 'rb').read(),
                        sys.argv[1])

    if True:

        dlg.ShowModal()

    else:

        import hotshot

        f=hotshot.Profile("hexeprof",1)

        f.runcall(dlg.ShowModal)

        f.close()

        import hotshot.stats

        stats=hotshot.stats.load("hexeprof")

        stats.strip_dirs()

        stats.sort_stats("time", "calls")

        stats.print_stats(30)

    dlg.Destroy()

    sys.exit(0)


if __name__=='__main__':

    import sys

    if len(sys.argv)!=2:

        print 'Usage:',sys.argv[0],'<File Name>'

        sys.exit(1)

    app=wx.PySimpleApp()

    dlg=HexEditorDialog(None, file(sys.argv[1], 'rb').read(),
                        sys.argv[1])

    if True:

        dlg.ShowModal()

    else:

        import hotshot

        f=hotshot.Profile("hexeprof",1)

        f.runcall(dlg.ShowModal)

        f.close()

        import hotshot.stats

        stats=hotshot.stats.load("hexeprof")

        stats.strip_dirs()

        stats.sort_stats("time", "calls")

        stats.print_stats(30)

    dlg.Destroy()

    sys.exit(0)
示例#12
0
    def detect(self, using_port=None, using_model=None):
        # start the detection process
        # 1st, get the list of available ports
        coms = comscan.comscan() + usbscan.usbscan()
        self.log('coms:' + str(coms))
        available_modem_coms=[x['name'] for x in coms if x['available'] \
                              and x.get('class', None)=='modem']
        if not using_port:
            available_coms = [x['name'] for x in coms if x['available']]
        else:
            available_coms = [using_port]
            available_modem_coms = [
                x for x in available_coms if x in available_modem_coms
            ]
        # loop through each port and gather data
        self.log('Available ports: ' + str(available_coms))
        self.log('Available modem ports: ' + str(available_modem_coms))
        # only try those AT commands on modem ports
        # using threads
        self.__q_on = True
        threads=[threading.Thread(target=self.do_get_data, args=(e,)) \
                 for e in available_modem_coms]
        for t in threads:
            t.start()
        for t in threads:
            t.join()
        self.__q_on = False
        while not self.__q_log.empty():
            q = self.__q_log.get_nowait()
            if isinstance(q, (list, tuple)):
                self.logdata(*q)
            else:
                self.log(q)
        # non-thread version
##        for e in available_modem_coms:
##            self.do_get_data(e)
# go through each phone and ask it
##        pm=phones.phonemodels
        if using_model:
            models = [using_model]
        else:
            models = phones.phonemodels
        found_port = found_model = None
        for model in models:
            self.log('Checking for model: ' + model)
            module = common.importas(phones.module(model))
            # check for detectphone in module.Phone or
            # phone_model and phone_manufacturer in module.Profile
            if hasattr(module.Phone, 'detectphone'):
                if using_port is None:
                    likely_ports=[x['name'] for x in coms if \
                                  x['available'] and \
                                  comdiagnose.islikelyport(x, module)]
                else:
                    likely_ports = [using_port]
                self.log('Likely ports:' + str(likely_ports))
                found_port = getattr(module.Phone,
                                     'detectphone')(coms, likely_ports,
                                                    self.__data, module, self)
                self.log('Detect Phone result: ' + ` self.__data `)
                if found_port is not None:
                    self.log('Phone ' + model + ' returned port:' +
                             ` found_port `)
                    # found it
                    found_model = model
                    break
            found_port = self.__check_profile(module.Profile)
            if found_port is not None:
                found_model = model
                break
        if found_port is None and using_port is None and using_model is None:
            # if we're not looking for a specific model on a specific port,
            # scan for other CDMA phone
            found_port, found_model = self.__check_for_other_cdma()
        if found_port is not None and found_model is not None:
            self.log('Found phone:' + found_model + ' port:' + ` found_port `)
            return {
                'port': found_port,
                'phone_name': found_model,
                'phone_module': phones.module(found_model),
                'phone_esn': self.__data[found_port]['esn']
            }
示例#13
0
    # if we are on windows check to see if this phone supports bluetooth as we may have a bluetooth comport
    # we check that the bluetooth device contains the manufacturers ID for the phone, this filters
    # other bluetooth devices from the search, on windows the 'hardwareinstance' contains BTHENUM indicating
    # a bluetooth device and the manufacturer's ID
    if sys.platform=='win32' and (getattr(phonemodule.Profile, 'bluetooth_mfg_id', 0) != 0) and \
        port['hardwareinstance'].find('BTHENUM\\')==0 and \
        port['hardwareinstance'].find(getattr(phonemodule.Profile, 'bluetooth_mfg_id', 'XXX'))>0:
        return score

    # ok, not then
    return -1


def autoguessports(phonemodule):
    """Returns a list of ports (most likely first) for finding the phone on"""
    # this function also demonsrates the use of list comprehensions :-)
    res = []
    # we only care about available ports
    ports = [(islikelyportscore(port, phonemodule), port)
             for port in comscan.comscan() + usbscan.usbscan() +
             bitflingscan.flinger.scan() if port['available']]
    # sort on score
    ports.sort()
    # return all ones with score >=0
    return [(port['name'], port) for score, port in ports if score >= 0]


if __name__ == '__main__':
    import common
    print autoguessports(common.importas("phones.com_lgvx4400"))
	def set(self, data):

        self._model_name=data.get('phone', '')

        self._model.SetLabel(self._model_name)

        self._com_port=data.get('com', '')

        self._port.SetLabel(self._com_port)

        _module=common.importas(phones.module(self._model_name))

        self._det_btn.Enable(bool(self._model_name and \
                                  hasattr(_module.Phone,
                                         'detectphone'))) 

    
	def OnDetect(self, _):

        if self._com_port=='auto':

            _port_name=None

        else:

            _port_name=str(self._com_port)

        _res=phone_detect.DetectPhone().detect(using_port=_port_name,
                                               using_model=self._model_name)

        _status='FAILED'

        if _res and _res.get('phone_name', '')==self._model_name:

            _status='PASSED'

        self._status.SetLabel(_status)



class  SetPhoneWizard (wiz.Wizard) :
	def __init__(self, parent):

        super(SetPhoneWizard, self).__init__(parent, -1,
                                             'Phone Setting Wizard')

        self._data={}

        commport_page=CommPortPage(self)

        phonemodel_page=PhoneModelPage(self)

        summary_page=SummaryPage(self)

        wiz.WizardPageSimple_Chain(commport_page, phonemodel_page)

        wiz.WizardPageSimple_Chain(phonemodel_page, summary_page)

        self.first_page=commport_page

        self.GetPageAreaSizer().Add(commport_page, 1, wx.EXPAND|wx.ALL, 5)

        wiz.EVT_WIZARD_PAGE_CHANGING(self, self.GetId(), self.OnPageChanging)

        wiz.EVT_WIZARD_PAGE_CHANGED(self, self.GetId(), self.OnPageChanged)

    
	def RunWizard(self, firstPage=None):

        return super(SetPhoneWizard, self).RunWizard(firstPage or self.first_page)

    
	def OnPageChanging(self, evt):

        pg=evt.GetPage()

        if not evt.GetDirection() or pg.ok():

            pg.get(self._data)

        else:

            evt.Veto()

    
	def OnPageChanged(self, evt):

        evt.GetPage().set(self._data)

    
	def get(self):

        return self._data



if __name__=="__main__":

    app=wx.PySimpleApp()

    f=wx.Frame(None, title='setphone_wizard')

    w=SetPhoneWizard(f)

    print w.RunWizard()

    print w._data

    w.Destroy()
示例#15
0
    def detect(self, using_port=None, using_model=None):
        # start the detection process
        # 1st, get the list of available ports
        coms=comscan.comscan()+usbscan.usbscan()
        self.log('coms:'+str(coms))
        available_modem_coms=[x['name'] for x in coms if x['available'] \
                              and x.get('class', None)=='modem']
        if not using_port:
            available_coms=[x['name'] for x in coms if x['available']]
        else:
            available_coms=[using_port]
            available_modem_coms=[x for x in available_coms if x in available_modem_coms]
        # loop through each port and gather data
        self.log('Available ports: '+str(available_coms))
        self.log('Available modem ports: '+str(available_modem_coms))
        # only try those AT commands on modem ports
        # using threads
        self.__q_on=True
        threads=[threading.Thread(target=self.do_get_data, args=(e,)) \
                 for e in available_modem_coms]
        for t in threads:
            t.start()
        for t in threads:
            t.join()
        self.__q_on=False
        while not self.__q_log.empty():
            q=self.__q_log.get_nowait()
            if isinstance(q, (list, tuple)):
                self.logdata(*q)
            else:
                self.log(q)
        # non-thread version
##        for e in available_modem_coms:
##            self.do_get_data(e)
        # go through each phone and ask it
##        pm=phones.phonemodels
        if using_model:
            models=[using_model]
        else:
            models=phones.phonemodels
        found_port=found_model=None
        for model in models:
            self.log('Checking for model: '+model)
            module=common.importas(phones.module(model))
            # check for detectphone in module.Phone or
            # phone_model and phone_manufacturer in module.Profile
            if hasattr(module.Phone, 'detectphone'):
                if using_port is None:
                    likely_ports=[x['name'] for x in coms if \
                                  x['available'] and \
                                  comdiagnose.islikelyport(x, module)]
                else:
                    likely_ports=[using_port]
                self.log('Likely ports:'+str(likely_ports))
                found_port=getattr(module.Phone, 'detectphone')(coms,
                                                                likely_ports,
                                                                self.__data,
                                                                module,
                                                                self)
                self.log('Detect Phone result: '+`self.__data`)
                if found_port is not None:
                    self.log('Phone '+model+' returned port:'+`found_port`)
                    # found it
                    found_model=model
                    break
            found_port=self.__check_profile(module.Profile)
            if found_port is not None:
                found_model=model
                break
        if found_port is None and using_port is None and using_model is None:
            # if we're not looking for a specific model on a specific port,
            # scan for other CDMA phone
            found_port, found_model=self.__check_for_other_cdma()
        if found_port is not None and found_model is not None:
            self.log('Found phone:'+found_model+' port:'+`found_port`)
            return { 'port': found_port, 'phone_name': found_model,
                     'phone_module': phones.module(found_model),
                     'phone_esn': self.__data[found_port]['esn'] }