⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tossimapp.py

📁 tinyos-2.x.rar
💻 PY
📖 第 1 页 / 共 2 页
字号:
        #if all types within the struct are already defined, it can be defined
        try :
          self.addType(nescStruct(self, typeDef ) )
          numSkipped=0

        except Exception, e:
          if len(e.args) > 0 and e.args[0] == "Undefined struct":
            #otherwise, put it back in the queue and move on to the next one
            typeDefs.append(typeDef)
            numSkipped += 1
          elif len(e.args) > 0 and e.args[0] == "Anonymous struct" :
            self.anonymousStructs.append(typeDef)
          elif len(e.args) > 0 and e.args[0] == "Anonymous struct reference" :
            self.anonymousRefStructs.append( (typeDef, e.args[1]) )
          elif len(e.args) > 0 and e.args[0] == "Unknown type" :
            self.unknownStructs.append( (typeDef, e.args[1]) )
          else :
            #if it's an unknown exception, reraise it
            raise
      
      #make sure we are not cycling endlessly
      if numSkipped >= len(typeDefs) > 0:
        self.undefinedTypes = typeDefs
        break

  def printSkippedTypes(self):
    err = ""
    if len(self.anonymousStructs) >0 :
      err += "\nWarning: %d structs were anonymous." % len(self.anonymousStructs)
#        for struc in anonymousStructs :
#            err += "\t%s\n" % struc.getAttribute("ref")
    if len(self.anonymousRefStructs) >0 :
      err += "\nWarning: The following structs referenced anonymous structs:\n"
      for pair in self.anonymousRefStructs :
        err += "\t%s\n" % pair[0].getAttribute("name")
    if len(self.undefinedTypes) >0 :
      err += "\nWarning: The following types are ill-defined or had circular dependencies:\n"
      for struc in self.undefinedTypes :
        err += "\t%s\n" % struc.getAttribute("name")
    if len(self.unknownStructs) >0 :
      err += "\nWarning: The following structs had unknown xml types:\n"
      for pair in self.unknownStructs :
        err += "\t%s (%s)\n" % (pair[0].getAttribute("name"),
                                pair[1].tagName )
    if len(err) > 0 : print err
    
  def getTypeFromXML(self, xmlDefinition) :
    """Find the type name value given an xml definition.
    If it is an array or pointer, define the new type here."""

    #first, see if the tag is type or if child is type
    if xmlDefinition.tagName.find("type-") < 0 or \
           xmlDefinition.tagName.find("type-qualified") >= 0 :
      foundType = 0
      childNodes = [node for node in xmlDefinition.childNodes
                    if node.nodeType == 1]
      for tag in childNodes :
        if tag.tagName.find("type-") >= 0 :
          foundType += 1
          typeTag = tag
      if foundType < 1 :
        raise Exception("No type tag found")
      if foundType > 1 :
        raise Exception("Too many type tags found")
      else :
        return self.getTypeFromXML(typeTag)

    #now check all the existing types to see if it is one of them
    for val in self._typeNames :
      typeObj = self._types[val]
      if typeObj.isType(xmlDefinition) :
        return deepcopy(typeObj)

    #if the type doesn't already exist, try creating a new one
    try :
      return nescArray(self, xmlDefinition)
    except Exception, e:
        if len(e.args) <= 0 or e.args[0] != "Not array definition":
          raise
    try :
      return nescPointer(self, xmlDefinition)
    except Exception, e:
        if len(e.args) <= 0 or e.args[0] != "Not pointer definition":
          raise
      
    #it is not a simple type, array, or pointer,
    #so it must be a yet undefined struct
    child = getUniqueChild(xmlDefinition)
    if ( xmlDefinition.tagName == "type-tag" and child != None and
         child.tagName == "struct-ref" ):
         if child.hasAttribute("name"):
             raise Exception("Undefined struct")
         else :
             raise Exception("Anonymous struct reference", child)
    else:
      #otherwise, raise an exception
      #(but first make sure the right kind of unknown type is displayed)
      if  xmlDefinition.tagName == "type-tag":
          xmlDefinition = child
      raise Exception("Unknown type", xmlDefinition)

class NescEnums( object ) :
  """A class that holds all enums defined in a specific nesc application.

  usage:
  myEnums = NescEnums('/path/to/nescDecls.xml')
  print myEnums
  var = myEnums.enumName
  """

  def __init__( self, applicationName="Unknown App", xmlFilename = None ) :
    self.applicationName = applicationName
    self._enums = []
    if type(xmlFilename) == str:
      xmlFilename = minidom.parse(xmlFilename)

    self.createEnumsFromXml(xmlFilename)

  def __getitem__(self, key) :
    if key in self._enums :
      return self.__dict__[key]
    else:
      raise AttributeError("No such enum defined")
      
  def createEnumsFromXml(self, dom) :

    #now define all the struct types
    enumDefs = [node for node in dom.getElementsByTagName("enum")]
    integer = re.compile('^I:(\d+)$')
    hexidecimal = re.compile('^(0x[\dabcdefABCDEF]+)$')
    
    for enumDef in enumDefs :
      name = enumDef.getAttribute("name")
      if name in self._enums :
        continue
      value = enumDef.getAttribute("value")
      match = integer.match(value)
      if match != None :
        self.__dict__[name] = int(match.groups()[0])
      else :
        match = hexidecimal.match(value)
        if match != None :
          self.__dict__[name] = int(match.groups()[0], 16)
        else :
          self.__dict__[name] = value
      self._enums.append(name)
      
    namedEnums = [node for node in dom.getElementsByTagName("namedEnum")]
    for namedEnum in namedEnums :
      name = namedEnum.getAttribute("name")
      self.__dict__[name] = NescEnums(namedEnum,name)
      self._enums.append(name)
    
  def __repr__(self) :
    return "%s object at %s:\n\n\t%s" % (self.__class__, hex(id(self)), str(self))
  
  def __str__(self) :
    """ Print all available enums."""
    string = "\n"
    for key in self._enums :
      string += "\t%s = %s\n" % (key, str(self[key]))
    return string
    

class NescMsgs( object ) :
  """A class that holds all msgs defined in a specific nesc application.
  It assumes a struct is a message if AM_STRUCTNAME is defined.

  usage:
  myMsgs = NescMsgs(myTypes, myEnums[, applicationName])
  print myMsgs
  var = myMsgs.msgName
  """
  def __init__( self, types, enums, applicationName="Unknown App" ) :
    self.applicationName = applicationName
    msgTypes = [enum for enum in enums._enums if enum.find("AM_") ==0]
    name = re.compile("^AM_(\w+)$")
    self._msgNames = []
    self._msgs = {}
    for msgType in msgTypes :
      if type(enums[msgType]) == int:
        msgName = name.match(msgType)
        if msgName != None :
          msgName = msgName.groups()[0]
        for key in types._typeNames :
          if key.lower() == msgName.lower() :
            msg = TosMsg(enums[msgType], types[key])
            self._msgs[key] = msg
            self._msgNames.append(key)
            break

  def __getattr__(self, name) :
    if name in self._msgNames :
      return deepcopy(self._msgs[name])
    else:
      raise AttributeError("No such message defined")
  
  def __getitem__(self, key) :
    if key in self._msgNames :
      return deepcopy(self._msgs[key])
    else:
      raise AttributeError("No such message defined")
      
  def __repr__(self) :
    return "%s object at %s:\n\n\t%s" % (self.__class__, hex(id(self)), str(self))
  
  def __str__(self) :
    """ Print all available msgs."""
    string = "\n"
    for key in self._msgNames :
      string += "\t%5d : %s\n" % (self._msgs[key].amType, key)
    return string
    

class NescApp( object ) :
  """A class that holds all types, enums, msgs, rpc commands and ram
  symbol definitions as defined for a specific nesc application.

  usage:
  myApp = nescApp('/path/to/nescDecls.xml')
  print myApp
  var = myApp.enums.enumName
  var = myApp.types.typeName
  """
  def __init__( self, applicationName="Unknown App", xmlFile="app.xml" ) :
    """This function creates the NescEnums, NescTypes, and NescMsgs
    objects for a particular application."""
    
    #first, import all enums, types, msgs, rpc functions, and ram symbols
    self.applicationName = applicationName
    self.xmlFile = xmlFile
    
    # Check for the nescDecls.xml file
    if not os.path.isfile(xmlFile):
      raise Exception("""\nERROR: cannot find file \"%s\".

Your nesC app cannot be imported.  Be sure that you compiled with the \"nescDecls\" option.\n\n""" % xmlFile)

    # Import enums, types, and msgs
    self.enums = NescEnums(applicationName, xmlFile)
    self.types = NescTypes(applicationName, xmlFile)
    self.variables = NescVariables(applicationName, xmlFile)
    self.messages = NescMsgs(self.types, self.enums, applicationName)

  def __repr__(self) :
    return "%s object at %s:\n\n%s" % (self.__class__, hex(id(self)), str(self))
  
  def __str__(self) :
    """ Print all application declarations."""
    string = "%20s : %d\n" % ("Enums", len(self.enums._enums))
    string += "%20s : %d\n" % ("Types", len(self.types._types))
    string += "%20s : %d\n" % ("Messages", len(self.messages._msgNames))
    string += "%20s : %d\n" % ("Variables", len(self.variables._varNames))
    return string

  def configureTossim(self):
    for var in variables:
      Mote.var

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -