autodetect on bluetooth

"Simon C" <[email protected]>
Newsgroups gmane.comp.mobile.bitpim.devel
Message-ID <000001c5ab6d$030c4d50$6400a8c0@HOME>
I've added some bluetooth autodetect for windows.
For phones that support bluetooth the bluetooth com ports will get added ot
the "likely_ports" passed to detect_phone.

I tested this with XP SP2 using the microsoft drivers, the drivers that came
with the BT adapter do not work with auto-detect, but it is possible that
some of the other propietry driver will work. Worse case it will not be able
to detect the phone and the user will have to manually configure it. It will
not work for other O/S, I deliberately coded it this way as I have no way to
test other O/Ss.

It works by knowing the manufacturer's ID of the phone and matching this
with the properties of the BT com port, this means that not just any
bluetooth device will get passed to detect_phone. I found that some
bluetooth com ports cause bitpim to hang when switching to brew mode, so you
cant just try all the BT ports found. Adding the BT manufacturer's ID to the
phones Profile enables autodetect for the BT ports for that model, I did
this for the vx8100.

Most of the change will not affect existing functionality, but the change to
comscan.py could, the "open" function does not work for BT ports, so I had
to change it to use the commport class in bp instead, if someone could check
this to make sure it is OK. I did test with a regular USB cable and it
seemed to be OK.

Code with diffs attached for commit.

Simon
comdiagnose.py (application/octet-stream, 11.7 KB)
#!/usr/bin/env python

### BITPIM
###
### Copyright (C) 2003-2004 Roger Binns <[email protected]>
###
### This program is free software; you can redistribute it and/or modify
### it under the terms of the BitPim license as detailed in the LICENSE file.
###
### $Id: comdiagnose.py,v 1.22 2004/08/18 08:21:06 rogerb Exp $

"""Generate opinions on the attached com devices"""

# Standard modules
import re
import sys

# My modules
import comscan
import usbscan
import bitflingscan

def diagnose(portlist, phonemodule):
    """Returns data suitable for use in com port settings dialog

    @param portlist: A list of ports as returned by L{comscan.comscan}()
    @return: A list of tuples (whattodisplay, portselected, htmldiagnosis)
    """
    res=[]
    # we sort into 3 lists
    # available
    # not available but active
    # the rest
    available=[]
    bfavailable=[]
    bfrest=[]
    notavailablebutactive=[]
    therest=[]
    for port in portlist:
        if port.has_key("available") and port["available"]:
            if port.has_key("BitFling"):
                bfavailable.append(port)
            else:
                available.append(port)
            continue
        if not port.has_key("BitFling") and (port.has_key("available") and port.has_key("active") and port["active"]):
            notavailablebutactive.append(port)
            continue
        if port.has_key("BitFling"):
            bfrest.append(port)
        else:
            therest.append(port)

    if len(available):
        whattodisplay="===== Available Ports ===== "
        portselected=None
        htmldiagnosis="<p>These ports are open and can be selected"
        res.append( (whattodisplay, portselected, htmldiagnosis) )
        for port in available:
            likely=islikelyport(port, phonemodule)
            whattodisplay=port['description']
            if likely:
                whattodisplay="(*) "+whattodisplay
            portselected=port['name']
            if likely:
                htmldiagnosis="<p>This port is likely to be your phone.  The port is available and can be selected.<p>"+genhtml(port)
            else:
                htmldiagnosis="<p>This port is available and can be selected.<p>"+genhtml(port)
            res.append( (whattodisplay, portselected, htmldiagnosis) )

    if len(notavailablebutactive):
        whattodisplay="===== Ports not available ====="
        portselected=None
        htmldiagnosis="<p>These ports are active, but cannot be used because they are in use by another program or device driver, you do not have permissions to access them, or a device driver is required."
        res.append( (whattodisplay, portselected, htmldiagnosis) )
        for port in notavailablebutactive:
            whattodisplay=port['description']
            portselected=port['name']
            htmldiagnosis="<p>This port is active but not available for use.<p>"+genhtml(port)
            res.append( (whattodisplay, portselected, htmldiagnosis) )
        
    if len(therest):
        whattodisplay="===== Inoperable Ports ====="
        portselected=None
        htmldiagnosis="""<p>These ports are known to your operating system, but cannot be used.  
        This may be because the device is not plugged in (such as on a USB to serial cable) or because 
        you don't have sufficient permissions to use them."""
        res.append( (whattodisplay, portselected, htmldiagnosis) )
        for port in therest:
            whattodisplay=port['description']
            portselected=port['name']
            htmldiagnosis="""<p>This port should not be selected.  If you believe it is the correct
            port, you should cause it to become available such as by plugging in the cable or ensuring
            you have correct permissions.  Press refresh once you have done so and it should be listed
            under available. Note that the name may change as it becomes available.<p>"""+genhtml(port)
            res.append( (whattodisplay, portselected, htmldiagnosis) )

    if len(bfavailable):
        whattodisplay="===== BitFling Available Ports ===== "
        portselected=None
        htmldiagnosis="<p>These BitFling ports are open and can be selected"
        res.append( (whattodisplay, portselected, htmldiagnosis) )
        for port in bfavailable:
            likely=islikelyport(port, phonemodule)
            whattodisplay=port['description']
            if likely:
                whattodisplay="(*) "+whattodisplay
            portselected=port['name']
            if likely:
                htmldiagnosis="<p>This port is likely to be your phone.  The port is available and can be selected.<p>"+genhtml(port)
            else:
                htmldiagnosis="<p>This port is available and can be selected.<p>"+genhtml(port)
            res.append( (whattodisplay, portselected, htmldiagnosis) )

    if len(bfrest):
        whattodisplay="===== BitFling Other Ports ===== "
        portselected=None
        htmldiagnosis="<p>These BitFling ports exist but are not available"
        res.append( (whattodisplay, portselected, htmldiagnosis) )
        for port in bfrest:
            likely=islikelyport(port, phonemodule)
            whattodisplay=port['description']
            if likely:
                whattodisplay="(*) "+whattodisplay
            portselected=port['name']
            if likely:
                htmldiagnosis="<p>This port is likely to be your phone.  The port is available and can be selected.<p>"+genhtml(port)
            else:
                htmldiagnosis="<p>This port is available and can be selected.<p>"+genhtml(port)
            res.append( (whattodisplay, portselected, htmldiagnosis) )


    return res

def htmlify(text):
    text=re.sub("&", "&amp;", text)
    text=re.sub("<", "&lt;", text)
    text=re.sub(">", "&gt;", text)
    return text

def genhtml(port):
    """Returns nice html describing a port dict"""
    sfont='<font size="-1">'
    efont='</font>'
    res='<table width="100%"><tr><th width="20%">Property<th width="40%">Value<th width="40%">Description</tr>\n'
    keys=port.keys()
    keys.sort()
    for k in keys:
        # property
        if k.startswith('usb-') and not k.endswith('string'):
            # ignore these
            continue
        res+='<tr><td valign="top">'+sfont+k+efont+'</td><td valign="top">\n'
        # value
        if k=='active' or k=='available':
            if port[k]:
                res+=sfont+"True"+efont
            else:
                res+=sfont+"False"+efont
        elif k=='driverdate':
            # XML-RPC converts tuples to lists, so we have to convert back again here
            res+=sfont+("%d-%d-%d" % tuple(port[k]))+efont
        elif k=='driverstatus':
            res+=sfont+`port[k]`+efont # should print it nicer at some point
        else:
            if isinstance(port[k], type("")):
                res+=sfont+htmlify(port[k])+efont
            else:
                res+=sfont+`port[k]`+efont
        res+='</td><td valign="top">'
        # description
        if k=='name':
            res+=sfont+"This is the name the port is known to your operating system as"+efont
        elif k=='available':
            if port[k]:
                res+=sfont+"It was possible to open this port"+efont
            else:
                res+=sfont+"It was not possible to open this port"+efont
        elif k=='active':
            if port[k]:
                res+=sfont+"Your operating system shows this driver and port is correctly configured and a device attached"+efont
            else:
                res+=sfont+"This driver/port combination is not currently running"+efont
        elif k=='driverstatus':
            res+=sfont+"""This is low level detail.  If problem is non-zero then you need to look in the
            control panel for an explanation as to why this driver/device is not working."""+efont
        elif k=='hardwareinstance':
            res+=sfont+"""This is how the device is named internally.  For example USB devices include
            the vendor (VID) and product (PID) identities"""+efont
        elif k=="libusb":
            res+=sfont+"""This indicates if the usb library is in use to access this device.  Operating system
            device drivers (if any) are bypassed when BitPim talks to the device"""+efont
        elif k=="driver-required":
            res+=sfont+"""This indicates if you must use a device driver, not direct USB access"""+efont
        elif k=="BitFling":
            res+=sfont+"""This indicates that the port is being accessed from a remote machine via BitFling,"""+efont
        elif k=="protocol":
            res+=sfont+"""This is the protocol the USB device claims to speak"""+efont
        elif k=="class":
            if port[k]=="serial":
                res+=sfont+"""This is a serial connection"""+efont
            elif port[k]=="modem":
                res+=sfont+"""This is a modem connection"""+efont
            else:
                res+=sfont+"""The port type (serial, modem etc)"""+efont
        else:
            res+="&nbsp;"

        # tail it
        res+="</td></tr>\n"

    res+="\n</table>"

    return res

def islikelyport(port, phonemodule):
    return islikelyportscore(port, phonemodule)>=0

def islikelyportscore(port, phonemodule):
    """Returns a port score.

    @return: -1 if no match, 0 best match, 1 next etc
    """

    usbids=phonemodule.Profile.usbids
    deviceclasses=phonemodule.Profile.deviceclasses

    # it must be the right class
    if port.has_key("class") and port["class"] not in deviceclasses:
        return -1

    score=0
    # check the usbids
    for vid,pid,iface in usbids:
        score+=1
        if port.has_key("libusb"):
            if port['usb-vendor#']==vid and \
                   port['usb-product#']==pid and \
                   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
    # did it have a usb id that didn't match?
    if port.has_key("libusb"):
        return -1

    # did the hardware instance have usb info?
    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

    # are we on non-windows platform?  if so, just be happy if 'usb' is in the name or the driver name
    if sys.platform!='win32' and ( \
        port['name'].lower().find('usb')>0 or port.get("driver","").lower().find('usb')>=0):
        return score

    # 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__':
    print autoguessports(__import__("com_lgvx4400"))
comdiagnose.py.diff (application/octet-stream, 1.1 KB)
Index: comdiagnose.py
===================================================================
RCS file: /cvsroot/bitpim/bitpim/comdiagnose.py,v
retrieving revision 1.22
diff -u -r1.22 comdiagnose.py
--- comdiagnose.py	18 Aug 2004 08:21:06 -0000	1.22
+++ comdiagnose.py	27 Aug 2005 22:26:22 -0000
@@ -259,6 +259,15 @@
         port['name'].lower().find('usb')>0 or port.get("driver","").lower().find('usb')>=0):
         return score
 
+    # 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
comscan.py (application/octet-stream, 18.4 KB)
#!/usr/bin/env python

### BITPIM
###
### Copyright (C) 2003-2004 Roger Binns <[email protected]>
###
### This program is free software; you can redistribute it and/or modify
### it under the terms of the BitPim license as detailed in the LICENSE file.
###
### $Id: comscan.py,v 1.19 2004/12/18 02:57:19 rogerb Exp $


"""Detect and enumerate com(serial) ports

You should close all com ports you have open before calling any
functions in this module.  If you don't they will be detected as in
use.

Call the comscan() function It returns a list with each entry being a
dictionary of useful information.  See the platform notes for what is
in each one.

For your convenience the entries in the list are also sorted into
an order that would make sense to the user.

Platform Notes:
===============

w  Windows9x
W  WindowsNT/2K/XP
L  Linux
M  Mac

wWLM name               string   Serial device name
wWLM available          Bool     True if it is possible to open this device
wW   active             Bool     Is the driver actually running?  An example of when this is False
                                 is USB devices or Bluetooth etc that aren't currently plugged in.
                                 If you are presenting stuff for users, do not show entries where
                                 this is false
w    driverstatus       dict     status is some random number, problem is non-zero if there is some
                                 issue (eg device disabled)
wW   hardwareinstance   string   instance of the device in the registry as named by Windows
wWLM description        string   a friendly name to show users
wW   driverdate         tuple    (year, month, day)
 W   driverversion      string   version string
wW   driverprovider     string   the manufacturer of the device driver
wW   driverdescription  string   some generic description of the driver
  L  device             tuple    (major, minor) device specification
  L  driver             string   the driver name from /proc/devices (eg ttyS or ttyUSB)
"""

version="$Revision: 1.19 $"

import sys
import os
import time
import glob
import commport

def _IsWindows():
    return sys.platform=='win32'

def _IsLinux():
    return sys.platform.startswith('linux')

def _IsMac():
    return sys.platform.startswith('darwin')

if _IsWindows():
    import _winreg

    class RegistryAccess:
        """A class that is significantly easier to use to access the Registry"""
        def __init__(self, hive=_winreg.HKEY_LOCAL_MACHINE):
            self.rootkey=_winreg.ConnectRegistry(None, hive)

        def getchildren(self, key):
            """Returns a list of the child nodes of a key"""
            k=_winreg.OpenKey(self.rootkey, key)
            index=0
            res=[]
            while 1:
                try:
                    subkey=_winreg.EnumKey(k, index)
                    res.append(subkey)
                    index+=1
                except:
                    # ran out of keys
                    break
            return res

        def safegetchildren(self, key):
            """Doesn't throw exception if doesn't exist

            @return: A list of zero or more items"""
            try:
                k=_winreg.OpenKey(self.rootkey, key)
            except:
                return []
            index=0
            res=[]
            while 1:
                try:
                    subkey=_winreg.EnumKey(k, index)
                    res.append(subkey)
                    index+=1
                except WindowsError,e:
                    if e[0]==259: # No more data is available
                        break
                    elif e[0]==234: # more data is available
                        index+=1
                        continue
                    raise
            return res


        def getvalue(self, key, node):
            """Gets a value

            The result is returned as the correct type (string, int, etc)"""
            k=_winreg.OpenKey(self.rootkey, key)
            v,t=_winreg.QueryValueEx(k, node)
            if t==2:
                return int(v)
            if t==3:
                # lsb data
                res=0
                mult=1
                for i in v:
                    res+=ord(i)*mult
                    mult*=256
                return res
            # un unicode if possible
            if isinstance(v, unicode):
                try:
                    return str(v)
                except:
                    pass
            return v

        def safegetvalue(self, key, node, default=None):
            """Gets a value and if nothing is found returns the default"""
            try:
                return self.getvalue(key, node)
            except:
                return default

        def findkey(self, start, lookfor, prependresult=""):
            """Searches for the named key"""
            res=[]
            for i in self.getchildren(start):
                if i==lookfor:
                    res.append(prependresult+i)
                else:
                    l=self.findkey(start+"\\"+i, lookfor, prependresult+i+"\\")
                    res.extend(l)
            return res

        def getallchildren(self, start, prependresult=""):
            """Returns a list of all child nodes in the hierarchy"""
            res=[]
            for i in self.getchildren(start):
                res.append(prependresult+i)
                l=self.getallchildren(start+"\\"+i, prependresult+i+"\\")
                res.extend(l)
            return res
            
def _comscanwindows():
    """Get detail about all com ports on Windows

    This code functions on both win9x and nt/2k/xp"""
    # give results back
    results={}
    resultscount=0
    
    # list of active drivers on win98
    activedrivers={}
    
    reg=RegistryAccess(_winreg.HKEY_DYN_DATA)
    k=r"Config Manager\Enum"
    for device in reg.safegetchildren(k):
        hw=reg.safegetvalue(k+"\\"+device, "hardwarekey")
        if hw is None:
            continue
        status=reg.safegetvalue(k+"\\"+device, "status", -1)
        problem=reg.safegetvalue(k+"\\"+device, "problem", -1)
        activedrivers[hw.upper()]={ 'status': status, 'problem': problem }

    # list of active drivers on winXP.  Apparently Win2k is different?
    reg=RegistryAccess(_winreg.HKEY_LOCAL_MACHINE)
    k=r"SYSTEM\CurrentControlSet\Services"
    for service in reg.safegetchildren(k):
        # we will just take largest number
        count=reg.safegetvalue(k+"\\"+service+"\\Enum", "Count", 0)
        next=reg.safegetvalue(k+"\\"+service+"\\Enum", "NextInstance", 0)
        for id in range(max(count,next)):
            hw=reg.safegetvalue(k+"\\"+service+"\\Enum", `id`)
            if hw is None:
                continue
            activedrivers[hw.upper()]=None


    # scan through everything listed in Enum.  Enum is the key containing a list of all
    # running hardware
    reg=RegistryAccess(_winreg.HKEY_LOCAL_MACHINE)

    # The three keys are:
    #
    #  - where to find hardware
    #    This then has three layers of children.
    #    Enum
    #     +-- Category   (something like BIOS, PCI etc)
    #           +-- Driver  (vendor/product ids etc)
    #                 +-- Instance  (An actual device.  You may have more than one instance)
    # 
    #  - where to find information about drivers.  The driver name is looked up in the instance
    #    (using the key "driver") and then looked for as a child key of driverlocation to find
    #    out more about the driver
    #
    #  - where to look for the portname key.  Eg in Win98 it is directly in the instance whereas
    #    in XP it is below "Device Parameters" subkey of the instance

    for enumstr, driverlocation, portnamelocation in ( 
            (r"SYSTEM\CurrentControlSet\Enum", r"SYSTEM\CurrentControlSet\Control\Class", r"\Device Parameters"),  # win2K/XP
            (r"Enum", r"System\CurrentControlSet\Services\Class", ""),   # win98
            ):
        for category in reg.safegetchildren(enumstr):
            catstr=enumstr+"\\"+category
            for driver in reg.safegetchildren(catstr):
                drvstr=catstr+"\\"+driver
                for instance in reg.safegetchildren(drvstr):
                    inststr=drvstr+"\\"+instance

                    # see if there is a portname
                    name=reg.safegetvalue(inststr+portnamelocation, "PORTNAME", "")

                    # We only want com ports
                    if len(name)<4 or name.lower()[:3]!="com":
                        continue

                    # Get rid of phantom devices
                    phantom=reg.safegetvalue(inststr, "Phantom", 0)
                    if phantom:
                        continue

                    # Lookup the class
                    klassguid=reg.safegetvalue(inststr, "ClassGUID")
                    if klassguid is not None:
                        # win2k uses ClassGuid
                        klass=reg.safegetvalue(driverlocation+"\\"+klassguid, "Class")
                    else:
                        # Win9x and WinXP use Class
                        klass=reg.safegetvalue(inststr, "Class")
                        
                    if klass is None:
                        continue
                    klass=klass.lower()
                    if klass=='ports':
                        klass='serial'
                    elif klass=='modem':
                        klass='modem'
                    else:
                        continue

                    # verify COM is followed by digits only
                    try:
                        portnum=int(name[3:])
                    except:
                        continue

                    # we now have some sort of match
                    res={}

                    res['name']=name.upper()
                    res['class']=klass

                    # is the device active?
                    kp=inststr[len(enumstr)+1:].upper()
                    if kp in activedrivers:
                        res['active']=True
                        if activedrivers[kp] is not None:
                            res['driverstatus']=activedrivers[kp]
                    else:
                        res['active']=False

                    # available?
                    if res['active']:
                        try:
                            usename=name
                            if sys.platform=='win32' and name.lower().startswith("com"):
                                usename="\\\\?\\"+name
                            commport.CommConnection(None, name, timeout=1).close()
                            res['available']=True
                        except Exception,e:
                            print usename,"is not available",e
                            res['available']=False
                    else:
                        res['available']=False

                    # hardwareinstance
                    res['hardwareinstance']=kp

                    # friendly name
                    res['description']=reg.safegetvalue(inststr, "FriendlyName", "<No Description>")

                    # driver information key
                    drv=reg.safegetvalue(inststr, "Driver")

                    if drv is not None:
                        driverkey=driverlocation+"\\"+drv

                        # get some useful driver information
                        for subkey, reskey in \
                            ("driverdate", "driverdate"), \
                            ("providername", "driverprovider"), \
                            ("driverdesc", "driverdescription"), \
                            ("driverversion", "driverversion"):
                            val=reg.safegetvalue(driverkey, subkey, None)
                            if val is None:
                                continue
                            if reskey=="driverdate":
                                try:
                                    val2=val.split('-')
                                    val=int(val2[2]), int(val2[0]), int(val2[1])
                                except:
                                    # ignroe wierd dates
                                    continue
                            res[reskey]=val

                    results[resultscount]=res
                    resultscount+=1


    return results

# There follows a demonstration of how user friendly Linux is.
# Users are expected by some form of magic to know exactly what
# the names of their devices are.  We can't even tell the difference
# between a serial port not existing, and there not being sufficient
# permission to open it
def _comscanlinux(maxnum=9):
    """Get all the ports on Linux

    Note that Linux doesn't actually provide any way to enumerate actual ports.
    Consequently we just look for device nodes.  It still isn't possible to
    establish if there are actual device drivers behind them.  The availability
    testing is done however.

    @param maxnum: The highest numbered device to look for (eg maxnum of 17
                   will look for ttyS0 ... ttys17)
    """

    # track of mapping majors to drivers
    drivers={}

    # get the list of char drivers from /proc/drivers
    f=open("/proc/devices", "r")
    f.readline()  # skip "Character devices:" header
    for line in f.readlines():
        line=line.split()
        if len(line)!=2:
            break # next section
        major,driver=line
        drivers[int(major)]=driver
    f.close()

    # device nodes we have seen so we don't repeat them in listing
    devcache={}
    
    resultscount=0
    results={}
    for prefix, description, klass in ( 
        ("/dev/cua", "Standard serial port", "serial"), 
        ("/dev/ttyUSB", "USB to serial convertor", "serial"),
        ("/dev/ttyACM", "USB modem", "modem"),
        ("/dev/usb/ttyUSB", "USB to serial convertor", "serial"), 
        ("/dev/usb/tts/", "USB to serial convertor", "serial"),
        ("/dev/usb/acm/", "USB modem", "modem"),
        ("/dev/input/ttyACM", "USB modem", "modem")
        ):
        for num in range(maxnum+1):
            name=prefix+`num`
            if not os.path.exists(name):
                continue
            res={}
            res['name']=name
            res['class']=klass
            res['description']=description+" ("+name+")"
            dev=os.stat(name).st_rdev
            try:
                f=open(name, "rw")
                f.close()
                res['available']=True
            except:
                res['available']=False
            # linux specific, and i think they do funky stuff on kernel 2.6
            # there is no way to get these 'normally' from the python library
            major=(dev>>8)&0xff
            minor=dev&0xff
            res['device']=(major, minor)
            if drivers.has_key(major):
                res['driver']=drivers[major]

            if res['available']:
                if dev not in devcache or not devcache[dev][0]['available']:
                    results[resultscount]=res
                    resultscount+=1
                    devcache[dev]=[res]
                continue
            # not available, so add
            try:
                devcache[dev].append(res)
            except:
                devcache[dev]=[res]
    # add in one failed device type per major/minor
    for dev in devcache:
        if devcache[dev][0]['available']:
            continue
        results[resultscount]=devcache[dev][0]
        resultscount+=1
    return results


def _comscanmac():
    """Get all the ports on Mac
    
    Just look for /dev/cu.* entries, they all seem to populate here whether
    USB->Serial, builtin, bluetooth, etc...

    """
    
    resultscount=0
    results={}
    for name in glob.glob("/dev/cu.*"):
       res={}
       res['name']=name
       if name.upper().rfind("MODEM") >= 0:
           res['description']="Modem"+" ("+name+")"
           res['class']="modem"
       else:
           res['description']="Serial"+" ("+name+")"
           res['class']="serial"
       try:
          f=open(name, "rw")
          f.close()
          res['available']=True
       except:
          res['available']=False
       results[resultscount]=res
       resultscount+=1
    return results

##def availableports():
##    """Gets list of available ports

##    It is verified that the ports can be opened.

##    @note:   You must close any ports you have open before calling this function, otherwise they
##             will not be considered available.

##    @return: List of tuples.  Each tuple is (port name, port description) - the description is user
##             friendly.  The list is sorted.
##    """
##    pass

def _stringint(str):
    """Seperate a string and trailing number into a tuple

    For example "com10" returns ("com", 10)
    """
    prefix=str
    suffix=""

    while len(prefix) and prefix[-1]>='0' and prefix[-1]<='9':
        suffix=prefix[-1]+suffix
        prefix=prefix[:-1]

    if len(suffix):
        return (prefix, int(suffix))
    else:
        return (prefix, None)
        
def _cmpfunc(a,b):
    """Comparison function for two port names

    In particular it looks for a number on the end, and sorts by the prefix (as a
    string operation) and then by the number.  This function is needed because
    "com9" needs to come before "com10"
    """

    aa=_stringint(a[0])
    bb=_stringint(b[0])

    if aa==bb:
        if a[1]==b[1]:
            return 0
        if a[1]<b[1]:
            return -1
        return 1
    if aa<bb: return -1
    return 1

def comscan(*args, **kwargs):
    """Call platform specific version of comscan function"""
    res={}
    if _IsWindows():
        res=_comscanwindows(*args, **kwargs)
    elif _IsLinux():
        res=_comscanlinux(*args, **kwargs)
    elif _IsMac():
        res=_comscanmac(*args, **kwargs)
    else:
        raise Exception("unknown platform "+sys.platform)

    # sort by name
    keys=res.keys()
    declist=[ (res[k]['name'], k) for k in keys]
    declist.sort(_cmpfunc)

    return [res[k[1]] for k in declist]
    

if __name__=="__main__":
    res=comscan()

    output="ComScan "+version+"\n\n"

    for r in res:
        rkeys=r.keys()
        rkeys.sort()

        output+=r['name']+":\n"
        offset=0
        for rk in rkeys:
            if rk=='name': continue
            v=r[rk]
            if not isinstance(v, type("")): v=`v`
            op=' %s: %s ' % (rk, v)
            if offset+len(op)>78:
                output+="\n"+op
                offset=len(op)+1
            else:
                output+=op
                offset+=len(op)

        if output[-1]!="\n":
            output+="\n"
        output+="\n"
        offset=0

    print output
comscan.py.diff (application/octet-stream, 908 B)
Index: comscan.py
===================================================================
RCS file: /cvsroot/bitpim/bitpim/comscan.py,v
retrieving revision 1.19
diff -u -r1.19 comscan.py
--- comscan.py	18 Dec 2004 02:57:19 -0000	1.19
+++ comscan.py	27 Aug 2005 21:35:35 -0000
@@ -55,6 +55,7 @@
 import os
 import time
 import glob
+import commport
 
 def _IsWindows():
     return sys.platform=='win32'
@@ -288,7 +289,7 @@
                             usename=name
                             if sys.platform=='win32' and name.lower().startswith("com"):
                                 usename="\\\\?\\"+name
-                            open(usename, "rw").close()
+                            commport.CommConnection(None, name, timeout=1).close()
                             res['available']=True
                         except Exception,e:
                             print usename,"is not available",e
com_lgvx8100.py (application/octet-stream, 17.8 KB)
### BITPIM
###
### Copyright (C) 2003-2005 Roger Binns <[email protected]>
### Copyright (C) 2005 Simon Capper <[email protected]>
###
### This program is free software; you can redistribute it and/or modify
### it under the terms of the BitPim license as detailed in the LICENSE file.
###

"""Communicate with the LG VX8100 cell phone

The VX8100 is substantially similar to the VX7000 but also supports video.

"""

# standard modules
import re
import time
import cStringIO
import sha

# my modules
import common
import commport
import copy
import com_lgvx4400
import p_brew
import p_lgvx8100
import com_lgvx7000
import com_brew
import com_phone
import com_lg
import prototypes
import bpcalendar
import call_history
import sms
import memo


from prototypes import *



class Phone(com_lgvx7000.Phone):
    "Talk to the LG VX8100 cell phone"

    desc="LG-VX8100"

    protocolclass=p_lgvx8100
    serialsname='lgvx8100'

    builtinringtones= ('Low Beep Once', 'Low Beeps', 'Loud Beep Once', 'Loud Beeps', 'VZW Default Ringtone') + \
                      tuple(['Ringtone '+`n` for n in range(1,11)]) + \
                      ('No Ring',)

    ringtonelocations= (
        # type       index-file   size-file directory-to-use lowest-index-to-use maximum-entries type-major
        ( 'ringers', 'dload/my_ringtone.dat', 'dload/my_ringtonesize.dat', 'brew/16452/lk/mr', 100, 150, 1),
        )

    builtinwallpapers = () # none

    wallpaperlocations= (
        ( 'images', 'dload/image.dat', 'dload/imagesize.dat', 'brew/16452/mp', 100, 50, 0),
        )
        
    def __init__(self, logtarget, commport):
        com_lgvx4400.Phone.__init__(self, logtarget, commport)
        self.mode=self.MODENONE

    def getfundamentals(self, results):
        """Gets information fundamental to interopating with the phone and UI.

        Currently this is:

          - 'uniqueserial'     a unique serial number representing the phone
          - 'groups'           the phonebook groups
          - 'wallpaper-index'  map index numbers to names
          - 'ringtone-index'   map index numbers to ringtone names

        This method is called before we read the phonebook data or before we
        write phonebook data.
        """

        # use a hash of ESN and other stuff (being paranoid)
        self.log("Retrieving fundamental phone information")
        self.log("Phone serial number")
        results['uniqueserial']=sha.new(self.getfilecontents("nvm/$SYS.ESN")).hexdigest()
        # now read groups
        self.log("Reading group information")
        buf=prototypes.buffer(self.getfilecontents("pim/pbgroup.dat"))
        g=self.protocolclass.pbgroups()
        g.readfrombuffer(buf)
        self.logdata("Groups read", buf.getdata(), g)
        groups={}
        for i in range(len(g.groups)):
            if len(g.groups[i].name): # sometimes have zero length names
                groups[i]={'name': g.groups[i].name }
        results['groups']=groups
        self.getwallpaperindices(results)
        self.getringtoneindices(results)
        self.log("Fundamentals retrieved")
        return results

    def savegroups(self, data):
        groups=data['groups']
        keys=groups.keys()
        keys.sort()
        g=self.protocolclass.pbgroups()
        for k in keys:
            e=self.protocolclass.pbgroup()
            e.name=groups[k]['name']
            g.groups.append(e)
        buffer=prototypes.buffer()
        g.writetobuffer(buffer)
        self.logdata("New group file", buffer.getvalue(), g)
        self.writefile("pim/pbgroup.dat", buffer.getvalue())

    def getmemo(self, result):
        # read the memo file
        try:
            buf=prototypes.buffer(self.getfilecontents("sch/neomemo.dat"))
            text_memo=self.protocolclass.textmemofile()
            text_memo.readfrombuffer(buf)
            res={}
            for m in text_memo.items:
                entry=memo.MemoEntry()
                entry.text=m.text
                entry.set_date_isostr("%d%02d%02dT%02d%02d00" % ((m.memotime)))
                res[entry.id]=entry
        except com_brew.BrewNoSuchFileException:
            res={}
        result['memo']=res
        return result

    def savememo(self, result, merge):
        text_memo=self.protocolclass.textmemofile()
        memo_dict=result.get('memo', {})
        keys=memo_dict.keys()
        keys.sort()
        text_memo.itemcount=len(keys)
        for k in keys:
            entry=self.protocolclass.textmemo()
            entry.text=memo_dict[k].text
            t=time.strptime(memo_dict[k].date, '%b %d, %Y %H:%M')
            entry.memotime=(t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min)
            text_memo.items.append(entry)
        buf=prototypes.buffer()
        text_memo.writetobuffer(buf)
        self.writefile("sch/neomemo.dat", buf.getvalue())
        return result

    def getcalendar(self,result):
        res={}
        # Read exceptions file first
        try:
            buf=prototypes.buffer(self.getfilecontents("sch/newschexception.dat"))
            ex=self.protocolclass.scheduleexceptionfile()
            ex.readfrombuffer(buf)
            self.logdata("Calendar exceptions", buf.getdata(), ex)
            exceptions={}
            for i in ex.items:
                try:
                    exceptions[i.pos].append( (i.year,i.month,i.day) )
                except KeyError:
                    exceptions[i.pos]=[ (i.year,i.month,i.day) ]
        except com_brew.BrewNoSuchFileException:
            exceptions={}

        # Now read schedule
        try:
            buf=prototypes.buffer(self.getfilecontents("sch/newschedule.dat"))
            if len(buf.getdata())<3:
                # file is empty, and hence same as non-existent
                raise com_brew.BrewNoSuchFileException()
            sc=self.protocolclass.schedulefile()
            self.logdata("Calendar", buf.getdata(), sc)
            sc.readfrombuffer(buf)
            for event in sc.events:
                # the vx8100 has a bad entry when the calender is empty
                # stop processing the calender when we hit this record
                if event.pos==0: #invalid entry
                    break                   
                entry=bpcalendar.CalendarEntry()
                entry.description=event.description
                entry.start=event.start
                entry.end=event.end
                entry.vibrate=~(event.alarmindex_vibrate&0x1) # vibarate bit is inverted in phone 0=on, 1=off
                entry.repeat = self.makerepeat(event.repeat)
                min=event.alarmminutes
                hour=event.alarmhours
                if min==0x64 or hour==0x64:
                    entry.alarm=None # no alarm set
                else:
                    entry.alarm=hour*60+min
                entry.ringtone=result['ringtone-index'][event.ringtone]['name']
                entry.snoozedelay=0
                # check for exceptions and remove them
                if event.repeat[3] and exceptions.has_key(event.pos):
                    for year, month, day in exceptions[event.pos]:
                        entry.suppress_repeat_entry(year, month, day)
                res[entry.id]=entry

            assert sc.numactiveitems==len(res)
        except com_brew.BrewNoSuchFileException:
            pass # do nothing if file doesn't exist
        result['calendar']=res
        return result

    def makerepeat(self, repeat):
        # get all the variables out of the repeat tuple
        # and convert into a bpcalender RepeatEntry
        type,dow,interval,exceptions=repeat
        if type==0:
            repeat_entry=None
        else:
            repeat_entry=bpcalendar.RepeatEntry()
            if type==1: #daily
                repeat_entry.repeat_type=repeat_entry.daily
                repeat_entry.interval=interval
            elif type==5: #'monfri'
                repeat_entry.repeat_type=repeat_entry.daily
                repeat_entry.interval=0
            elif type==2: #'weekly'
                repeat_entry.repeat_type=repeat_entry.weekly
                repeat_entry.dow=dow
                repeat_entry.interval=interval
            elif type==3: #'monthly'
                repeat_entry.repeat_type=repeat_entry.monthly
                repeat_entry.interval=interval
                repeat_entry.dow=0
            elif type==6: #'monthly' #Xth Y day (e.g. 2nd friday each month)
                repeat_entry.repeat_type=repeat_entry.monthly
                repeat_entry.interval=interval #X
                repeat_entry.dow=dow #Y
            else: # =4 'yearly'
                repeat_entry.repeat_type=repeat_entry.yearly
        return repeat_entry

    def savecalendar(self, dict, merge):
        # ::TODO::
        # what will be written to the files
        eventsf=self.protocolclass.schedulefile()
        exceptionsf=self.protocolclass.scheduleexceptionfile()

        # what are we working with
        cal=dict['calendar']
        newcal={}
        keys=cal.keys()
        keys.sort()
        pos=1

        # number of entries
        eventsf.numactiveitems=len(keys)
        
        # play with each entry
        for k in keys:
            # entry is what we will return to user
            entry=cal[k]
            data=self.protocolclass.scheduleevent()
            data.pos=eventsf.packetsize()
            data.description=entry.description
            data.start=entry.start
            data.end=entry.end
            self.setalarm(entry, data)
            data.ringtone=0
            for i in dict['ringtone-index']:
                if dict['ringtone-index'][i]['name']==entry.ringtone:
                    data.ringtone=i
            # check for exceptions and add them to the exceptions list
            exceptions=0
            if entry.repeat!=None:
                for i in entry.repeat.suppressed:
                    de=self.protocolclass.scheduleexception()
                    de.pos=data.pos
                    de.day=i.date.day
                    de.month=i.date.month
                    de.year=i.date.year
                    exceptions=1
                    exceptionsf.items.append(de)
            if entry.repeat != None:
                data.repeat=(self.getrepeattype(entry, exceptions))
            else:
                data.repeat=((0,0,0,0))

            data.unknown1=0
            data.unknown2=0

            # put entry in nice shiny new dict we are building
            entry=copy.copy(entry)
            newcal[data.pos]=entry
            eventsf.events.append(data)

        # scribble everything out
        buf=prototypes.buffer()
        eventsf.writetobuffer(buf)
        self.logdata("Writing calendar", buf.getvalue(), eventsf)
        self.writefile("sch/newschedule.dat", buf.getvalue())
        buf=prototypes.buffer()
        exceptionsf.writetobuffer(buf)
        self.logdata("Writing calendar exceptions", buf.getvalue(), exceptionsf)
        self.writefile("sch/newschexception.dat", buf.getvalue())

        # fix passed in dict
        dict['calendar']=newcal

        return dict

    def getrepeattype(self, entry, exceptions):
        #convert the bpcalender type into vx8100 type
        repeat_entry=bpcalendar.RepeatEntry()
        if entry.repeat.repeat_type==repeat_entry.monthly:
            dow=entry.repeat.dow
            if entry.repeat.dow==0:
                # set interval for month type 4 to start day of month, (required by vx8100)
                interval=entry.start[2]
                type=3
            else:
                interval=entry.repeat.interval
                type=6
        elif entry.repeat.repeat_type==repeat_entry.daily:
            dow=entry.repeat.dow
            interval=entry.repeat.interval
            if entry.repeat.interval==0:
                type=5
            else:
                type=1
        elif entry.repeat.repeat_type==repeat_entry.weekly:
            dow=entry.repeat.dow
            interval=entry.repeat.interval
            type=2
        elif entry.repeat.repeat_type==repeat_entry.yearly:
            # set interval to start day of month, (required by vx8100)
            interval=entry.start[2]
            # set dow to start month, (required by vx8100)
            dow=entry.start[1]
            type=4
        return (type, dow, interval, exceptions)

    def setalarm(self, entry, data):
        # vx8100 only allows certain repeat intervals, adjust to fit, it also stores an index to the interval
        if entry.alarm>=2880:
            entry.alarm=2880
            data.alarmminutes=0
            data.alarmhours=48
            data.alarmindex_vibrate=0x10
        elif entry.alarm>=1440:
            entry.alarm=1440
            data.alarmminutes=0
            data.alarmhours=24
            data.alarmindex_vibrate=0xe
        elif entry.alarm>=120:
            entry.alarm=120
            data.alarmminutes=0
            data.alarmhours=2
            data.alarmindex_vibrate=0xc
        elif entry.alarm>=60:
            entry.alarm=60
            data.alarmminutes=0
            data.alarmhours=1
            data.alarmindex_vibrate=0xa
        elif entry.alarm>=15:
            entry.alarm=15
            data.alarmminutes=15
            data.alarmhours=0
            data.alarmindex_vibrate=0x8
        elif entry.alarm>=10:
            entry.alarm=10
            data.alarmminutes=10
            data.alarmhours=0
            data.alarmindex_vibrate=0x6
        elif entry.alarm>=5:
            entry.alarm=5
            data.alarmminutes=10
            data.alarmhours=0
            data.alarmindex_vibrate=0x4
        elif entry.alarm>=0:
            entry.alarm=0
            data.alarmminutes=0
            data.alarmhours=0
            data.alarmindex_vibrate=0x2
        else: # no alarm
            data.alarmminutes=0x64
            data.alarmhours=0x64
            data.alarmindex_vibrate=1

        # set the vibrate bit
        if data.alarmindex_vibrate > 1 and entry.vibrate==0:
            data.alarmindex_vibrate+=1
        return

    my_model='VX8100'

    def getphoneinfo(self, phone_info):
        self.log('Getting Phone Info')
        try:
            s=self.getfilecontents('brew/version.txt')
            if s[:6]=='VX8100':
                phone_info.append('Model:', "VX8100")
                req=p_brew.firmwarerequest()
                res=self.sendbrewcommand(req, self.protocolclass.firmwareresponse)
                phone_info.append('Firmware Version:', res.firmware)
                s=self.getfilecontents("nvm/$SYS.ESN")[85:89]
                txt='%02X%02X%02X%02X'%(ord(s[3]), ord(s[2]), ord(s[1]), ord(s[0]))
                phone_info.append('ESN:', txt)
                txt=self.getfilecontents("nvm/nvm/nvm_cdma")[180:190]
                phone_info.append('Phone Number:', txt)
        except:
            pass
        return


parentprofile=com_lgvx7000.Profile
class Profile(parentprofile):
    protocolclass=Phone.protocolclass
    serialsname=Phone.serialsname

    BP_Calendar_Version=3
    phone_manufacturer='LG Electronics Inc'
    phone_model='VX8100'

    WALLPAPER_WIDTH=176
    WALLPAPER_HEIGHT=184
    MAX_WALLPAPER_BASENAME_LENGTH=32
    WALLPAPER_FILENAME_CHARS="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ."
    WALLPAPER_CONVERT_FORMAT="jpg"
   
    MAX_RINGTONE_BASENAME_LENGTH=32
    RINGTONE_FILENAME_CHARS="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ."

    # there is an origin named 'aod' - no idea what it is for except maybe
    # 'all other downloads'

    # the vx8100 supports bluetooth for connectivity to the PC, define the "bluetooth_mgd_id"
    # to enable bluetooth discovery during phone detection
    # the bluetooth address starts with LG's the three-octet OUI, all LG phone
    # addresses start with this, it provides a way to identify LG bluetooth devices
    # during phone discovery
    # OUI=Organizationally Unique Identifier
    # see http://standards.ieee.org/regauth/oui/index.shtml for more info
    bluetooth_mfg_id="001256"

    # the 8100 doesn't have seperate origins - they are all dumped in "images"
    imageorigins={}
    imageorigins.update(common.getkv(parentprofile.stockimageorigins, "images"))
    def GetImageOrigins(self):
        return self.imageorigins

    # our targets are the same for all origins
    imagetargets={}
    imagetargets.update(common.getkv(parentprofile.stockimagetargets, "wallpaper",
                                      {'width': 176, 'height': 184, 'format': "JPEG"}))
    imagetargets.update(common.getkv(parentprofile.stockimagetargets, "pictureid",
                                      {'width': 176, 'height': 184, 'format': "JPEG"}))
    imagetargets.update(common.getkv(parentprofile.stockimagetargets, "outsidelcd",
                                      {'width': 96, 'height': 80, 'format': "JPEG"}))
    imagetargets.update(common.getkv(parentprofile.stockimagetargets, "fullscreen",
                                      {'width': 176, 'height': 220, 'format': "JPEG"}))

    def GetTargetsForImageOrigin(self, origin):
        return self.imagetargets

 
    def __init__(self):
        parentprofile.__init__(self)

    _supportedsyncs=(
        ('phonebook', 'read', None),   # all phonebook reading
        ('calendar', 'read', None),    # all calendar reading
        ('wallpaper', 'read', None),   # all wallpaper reading
        ('ringtone', 'read', None),    # all ringtone reading
        ('call_history', 'read', None),# all call history list reading
        ('sms', 'read', None),         # all SMS list reading
        ('memo', 'read', None),        # all memo list reading
        ('phonebook', 'write', 'OVERWRITE'),  # only overwriting phonebook
        ('calendar', 'write', 'OVERWRITE'),   # only overwriting calendar
        ('wallpaper', 'write', 'MERGE'),      # merge and overwrite wallpaper
        ('wallpaper', 'write', 'OVERWRITE'),
        ('ringtone', 'write', 'MERGE'),       # merge and overwrite ringtone
        ('ringtone', 'write', 'OVERWRITE'),
        ('sms', 'write', 'OVERWRITE'),        # all SMS list writing
        ('memo', 'write', 'OVERWRITE'),       # all memo list writing
        )
com_lgvx8100.py.diff (application/octet-stream, 1.1 KB)
Index: com_lgvx8100.py
===================================================================
RCS file: /cvsroot/bitpim/bitpim/com_lgvx8100.py,v
retrieving revision 1.4
diff -u -r1.4 com_lgvx8100.py
--- com_lgvx8100.py	24 Aug 2005 04:14:43 -0000	1.4
+++ com_lgvx8100.py	27 Aug 2005 21:30:24 -0000
@@ -431,6 +431,15 @@
     # there is an origin named 'aod' - no idea what it is for except maybe
     # 'all other downloads'
 
+    # the vx8100 supports bluetooth for connectivity to the PC, define the "bluetooth_mgd_id"
+    # to enable bluetooth discovery during phone detection
+    # the bluetooth address starts with LG's the three-octet OUI, all LG phone
+    # addresses start with this, it provides a way to identify LG bluetooth devices
+    # during phone discovery
+    # OUI=Organizationally Unique Identifier
+    # see http://standards.ieee.org/regauth/oui/index.shtml for more info
+    bluetooth_mfg_id="001256"
+
     # the 8100 doesn't have seperate origins - they are all dumped in "images"
     imageorigins={}
     imageorigins.update(common.getkv(parentprofile.stockimageorigins, "images"))
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.