Ejemplo n.º 1
0
 def __populate( self, metainfo ):
     # a torent file may have a single tracker, multiple trackers,
     # or both a reference to a single tracker and multiple trackers (for backwards compatibility)
     if 'announce' in metainfo:
         # single tracker
         self.trackerURLs.add( metainfo[ 'announce' ] )
     if 'announce-list' in metainfo:
         # multiple trackers
         self.trackerURLs |= set( utilities.flatten( metainfo[ 'announce-list' ] ) )
     if 'created by' in metainfo:
         self.createdBy = metainfo[ 'created by' ]
     if 'comment' in metainfo:
         self.comment = metainfo[ 'comment' ]
     if 'encoding' in metainfo:
         self.encoding = metainfo[ 'encoding' ]
     if 'creation date' in metainfo:
         self.creationDate = datetime.datetime.fromtimestamp( metainfo[ 'creation date' ] )
     if 'files' in metainfo[ 'info' ]:
         # multi file mode
         self.singleFile = False
         self.name = metainfo[ 'info' ][ 'name' ]
         self.files = []
         for file in metainfo[ 'info' ][ 'files' ]:
             self.files.append( File( file[ 'path' ], file[ 'length' ] ) )
     if 'length' in metainfo[ 'info' ]:
         # single file mode
         self.singleFile = True
         self.name = metainfo[ 'info' ][ 'name' ]
         self.files = [ File( [ metainfo[ 'info' ][ 'name' ] ], metainfo[ 'info' ][ 'length' ] ) ]
Ejemplo n.º 2
0
    def decode(self, packet):
        """ Decodes a the response

        :param packet: The packet data to decode
        """
        count, self.records = 1, []

        self.frame = packet
        ########################################################
        # Do not include DLE STX and DLE ETX CRC in calcualtion
        ########################################################
        data = packet[2:-4]

        #############################################
        # Calculate CRC after removing escaped DLE's
        #############################################
        crc, = struct.unpack(">H", packet[-2:])
        if utilities.checkCRC(data, crc) != True:
            raise CRCException("Error in CRC : %d" % crc)

        ############################
        # Packet Header Information
        ############################
        self.dest, self.src, self.command, self.sts, self.transaction_id = struct.unpack(">BBBBH", data[0:6])
        data = data[6:]

        #####################################
        # Packet data Information
        # Use Little Endian format for data
        #####################################
        self.records = ()
        if len(data) > 0:
            if self.Address.subElement > 0:
                elementSize = SUBELEMENT_SIZE[self.Address.fileType]
                formatStr = "<" + SUBELEMENT_STRUCT[self.Address.fileType]
            else:
                elementSize = ELEMENT_SIZE[self.Address.fileType]
                formatStr = "<" + ELEMENT_STRUCT[self.Address.fileType]

            for i in range(0, len(data), elementSize):
                if self.Address.bitNumber != None:
                    register, = struct.unpack(formatStr, data[i : i + elementSize])
                    if register & 2 ** self.Address.bitNumber:
                        self.records += (1,)
                    else:
                        self.records += (0,)
                else:
                    if self.Address.fileType == 0x8D:
                        record, = struct.unpack(formatStr, data[i : i + elementSize])
                        size, = struct.unpack("<h", record[0:2])
                        newRecord = ""
                        for i in range(2, elementSize, 2):
                            newRecord += record[i + 1] + record[i]
                        self.records += (newRecord[0:size],)
                    else:
                        self.records += struct.unpack(formatStr, data[i : i + elementSize])

            self.records = utilities.flatten(self.records)
        else:
            self.records = None
Ejemplo n.º 3
0
def encode( data ):
    if type( data ) is str:
        return str( len( data ) ) + ':' + data
    if type( data ) is int:
        return 'i' + str( data ) + 'e'
    if type( data ) is list:
        return 'l' + ''.join( map( encode, data ) ) + 'e'
    if type( data ) is dict:
        flattened = utilities.flatten( data.items() )
        encoded = map( encode, flattened )
        joined = ''.join( encoded )
        return 'd' + joined + 'e'
Ejemplo n.º 4
0
    def write(self, response):
        ''' Write the data to the specified file

        :param response: The response to process
        '''
        data = []
        for item in response:
            data.append(item)
        response = utilities.flatten(data)
        currentTime = time.localtime()
        stringData = time.strftime('%m/%d/%Y,', currentTime)
        stringData += time.strftime('%T,', currentTime)
        stringData += ','.join(map(str, response))
        stringData += '\n'
        logName = self.logFile.write(stringData)
        if (self.fileName != logName):
            self.fileName = logName
Ejemplo n.º 5
0
    def evaluateBits(self, alarmBits):
        bits = utilities.flatten(alarmBits)
        if (bits[0]):
            # self.notified added so multiple emails won't be sent
            if (not self.notified):
                serialLog.debug("Sending Email notice of Error")
                strMsg = ''
                if (bits[0] & 1):
                    """ Temperature Too High Alarm """
                    strMsg += "Temperature has reached a critical point\n"

                if (bits[0] & 2):
                    """ Motor Amps exceeded threshold """
                    strMsg += "TU Motor Current has exceeded baseline threshold\n"

                if (bits[0] & 4):
                    """ Vibration exceeds threshold """
                    strMsg += "Vibration sensor readings outside of acceptable tolerance\n"

                if (bits[0] & 8):
                    """ Speed variance outside of tolerance """
                    strMsg += "TU speed is varying more than specified tolerance\n"

                sender, recepient = self.config.getEmail()
                sendEmail(sender, recepient, strMsg, "Alert: Alarm")
                self.notified = True
        else:
            self.notified = False

        if (bits[1]):
            # self.loaded added so multiple uploads won't be initiated
            # TODO: Add code to load values to PLC
            if (not self.loaded):
                serialLog.debug("Loading Values to PLC")
                self.loaded = True

                def clearRecipeBit(response):
                    request = protectedBitWriteRequest(1, self.ALARMS[1], [0])
                    d = self.sendRequest(request)
                    d.addErrback(self.errorHandler, 'clearRecipeBit')


                def sendRecipe(recipe):
                    PLCRecipe = self.config.getPLCRecipe()

                    result = self.mtrimSerial.writeParameter(1, 1, float(recipe[-3]))
                    result.addErrback(self.errorHandler, "sendRecipe")

                    result = self.mtrimSerial.writeParameter(1, 20, float(recipe[-2]))
                    result.addErrback(self.errorHandler, "sendRecipe")

                    result = self.mtrimSerial.writeParameter(1, 21, float(recipe[-1]))
                    result.addErrback(self.errorHandler, "sendRecipe")

                    index = 1                               # Index 0 is recipe name
                    var = []
                    for address in PLCRecipe:
                        request = protectedWriteRequest(1, address, [float(recipe[index])])
                        result = self.sendRequest(request)
                        result.addErrback(self.errorHandler, "sendRecipe")
                        var.append(result)
                    d = defer.gatherResults(var)
                    d.addCallback(clearRecipeBit)
                    d.addErrback(self.errorHandler, 'saving data in StartOEEData failed')
                         
                def getRecipeValues(recipeName):
                    localDir, remoteDir = self.config.getRecipeDirectories()
                    filename = localDir + '/' + 'families.csv'
                    fObj = open(filename, 'r')
                    for recipe in fObj:
                        if recipe.strip() in recipeName[0]:
                            recipeFile = localDir + '/' + recipe.strip() + '.csv'
                            fRecipe = open(recipeFile, 'r')
                            for line in fRecipe:
                                if recipeName[0] in line.strip():
                                    sendRecipe(line.strip().split(','))
                                
                request = protectedReadRequest(1, 'ST15:20')
                d = self.sendRequest(request)
                d.addCallback(getRecipeValues)
                d.addErrback(self.errorHandler, 'saving recipe data')
                
        else:
            self.loaded = False
            

        if (bits[2]):
            # self.transferred added so multiple downloads won't be initiated
            def clearDownloadBit(response):
                request = protectedBitWriteRequest(1, self.ALARMS[2], [0])
                d = self.sendRequest(request)
                d.addErrback(self.errorHandler, 'clearDownloadBit')
               
            if (not self.transferred):
                #Download Recipes from Server
                localDir, remoteDir = self.config.getRecipeDirectories()
                serialLog.debug("Downloading Recipes")
                d = self.ftpEndpoint.connect(FTPClientAFactory())
                d.addErrback(self.FTPfail, 'startRecipeTransfer')
                d.addCallback(getRecipeFiles, localDir)
                d.addCallback(clearDownloadBit)
                self.transferred = True
        else:
            self.transferred = False
Ejemplo n.º 6
0
def generate_ufuncs(file, function_definitions, includes=[]):
    template = env.get_template("function_file.pyx")
    context = {"functions": flatten(function_definitions), "includes": includes}

    with open(file, "w") as f:
        f.write(template.render(**context))
Ejemplo n.º 7
0
# VARIABLES:
tags = {
	"LesHouchesEvents": {
		"event": {},
		"init": {},
		"header": {
			"MGVersion": {},
			"MG5ProcCard": {},
			"MGProcCard": {},
			"MGRunCard": {},
			"slha": {},
			"MCGenerationInfo": {},
		},
	},
}
tags_full = utilities.flatten(tags).keys()
tags_all = [tag_full.split("_")[-1] for tag_full in tags_full]
# :VARIABLES


# CLASSES:
class header:
	def __init__(self, lhe_string):
		match = re.search("(<header>[\s\S]*</header>)", lhe_string)
#		print lhe_string
#		print match
		if match:
			self.raw = match.group(1)
		else:
			self.raw = False