def Execute_Text_And_Title(root):

    # find the interface object type

    objectServerID = root.find("./OBJECTSERVERID").text
    objectFlags = root.find("./OBJECTFLAGS").text

    validate = Validate.checkForValidate(root)

    if Config.debug():
        print "VALIDATE=%s" % validate

    outgoingXMLData = BuildResponse.buildHeader(root)

    if Config.debug():
        print ("objectServerID = %s" % objectServerID)

    # we have the objectServerID so now we can choose the correct
    # program

    if objectServerID == "LT-1":

        # check for validate request
        if validate == "YES":
            outgoingXMLData += Validate.buildValidateResponse("YES")
            outgoingXMLData += BuildResponse.buildFooter()

            return outgoingXMLData

        output = subprocess.check_output(["cat", "/sys/class/thermal/thermal_zone0/temp"])
        FMOutput = float(output) / 1000.0

        responseData = "%3.2f, %3.2f, %s" % (FMOutput, FMOutput, "CPU Temp (deg C)")

        outgoingXMLData += BuildResponse.buildResponse(responseData)

    else:

        # invalid RaspiConnect Code
        outgoingXMLData += Validate.buildValidateResponse("NO")

    outgoingXMLData += BuildResponse.buildFooter()
    if Config.debug():
        print outgoingXMLData

    return outgoingXMLData
예제 #2
0
파일: Equiv.py 프로젝트: ninjin/TEES
def duplicateEquiv(event, duplDict, debug):
    """
    If the event (event tree) has arguments which have Equiv-statements, create a new event
    for each combination. Otherwise, return just the existing event.
    """
    argList = [] # depth-first argument list
    hasEquiv = getArgs(event, argList)
    if not hasEquiv:
        return [event]
    if debug:
        print "----------------------------------------------"
        print "Event:", event.id, event.type, event.arguments
        print " Orig. Duplicates:", argList
    combinations = combine.combine(*argList) # make all combinations
    if debug:
        print " Dup. Combinations:", combinations
    newEvents = []
    count = 0 # used only for marking duplicates' ids
    for combination in combinations:
        createdEvents = makeEvent(event, combination, count, duplDict=duplDict, debug=debug)
        newEvent = createdEvents[0]
        if debug:
            for createdEvent in createdEvents:
                if createdEvent == newEvent:
                    print " New Event (root):", createdEvent.id, createdEvent.type, createdEvent.arguments
                else:
                    print " New Event:", createdEvent.id, createdEvent.type, createdEvent.arguments
                Validate.validate([createdEvent], simulation=True)
        newEvents.append(newEvent)
        count += 1
    return newEvents
예제 #3
0
def duplicateEquiv(event, duplDict, debug):
    """
    If the event (event tree) has arguments which have Equiv-statements, create a new event
    for each combination. Otherwise, return just the existing event.
    """
    argList = []  # depth-first argument list
    hasEquiv = getArgs(event, argList)
    if not hasEquiv:
        return [event]
    if debug:
        print "----------------------------------------------"
        print "Event:", event.id, event.type, event.arguments
        print " Orig. Duplicates:", argList
    combinations = combine.combine(*argList)  # make all combinations
    if debug:
        print " Dup. Combinations:", combinations
    newEvents = []
    count = 0  # used only for marking duplicates' ids
    for combination in combinations:
        createdEvents = makeEvent(event,
                                  combination,
                                  count,
                                  duplDict=duplDict,
                                  debug=debug)
        newEvent = createdEvents[0]
        if debug:
            for createdEvent in createdEvents:
                if createdEvent == newEvent:
                    print " New Event (root):", createdEvent.id, createdEvent.type, createdEvent.arguments
                else:
                    print " New Event:", createdEvent.id, createdEvent.type, createdEvent.arguments
                Validate.validate([createdEvent], simulation=True)
        newEvents.append(newEvent)
        count += 1
    return newEvents
예제 #4
0
파일: STTools.py 프로젝트: jbjorne/Tdevel
def writeSet(documents, output, resultFileTag="a2", debug=False, task=2, validate=True, writeScores=False):
    from collections import defaultdict
    import shutil
    counts = defaultdict(int)
    
    while output.endswith("/"):
        output = output[:-1]
    if output.endswith(".tar.gz"):
        outdir = output + "-temp"
    else:
        outdir = output
    if os.path.exists(outdir):
        shutil.rmtree(outdir)

    if not validate:
        print "Warning! No validation."
    for doc in documents:
        if validate:
            if debug: print >> sys.stderr, "Validating", doc.id
            Validate.allValidate(doc, counts, task, verbose=debug)
        #doc.proteins.sort(cmp=compareOffsets)
        #doc.triggers.sort(cmp=compareOffsets)
        if debug: print >> sys.stderr, "Writing", doc.id
        write(doc.id, outdir, doc.proteins, doc.triggers, doc.events, doc.relations, resultFileTag, counts, task=task, writeScores=writeScores)
        # Write text file
        #out = open(os.path.join(outdir, str(doc.id) + ".txt"), "wt")
        out = codecs.open(os.path.join(outdir, str(doc.id) + ".txt"), "wt", "utf-8")
        out.write(doc.text)
        out.close()
    if output.endswith(".tar.gz"):
        package(outdir, output, ["a1", "txt", resultFileTag, resultFileTag+".scores"])
        shutil.rmtree(outdir)
    print counts
 def validate(self, inputFilesets):
     validate = Validate(self.config, self.db)
     validate.process(inputFilesets)
     for inp in inputFilesets:
         if os.path.isfile(inp.csvFilename):
             InputFileset.upload.append(inp)
         else:
             RunStatus.set(inp.filesetId, False)
def Execute_Single_LED(root):

	# find the interface object type

	objectServerID = root.find("./OBJECTSERVERID").text
	objectFlags = root.find("./OBJECTFLAGS").text

	validate = Validate.checkForValidate(root)

	if (Config.debug()):
		print("VALIDATE=%s" % validate)

	outgoingXMLData = BuildResponse.buildHeader(root)


	if (Config.debug()):
		print("objectServerID = %s" % objectServerID)

	# we have the objectServerID so now we can choose the correct
	# program

	# L-1 sends back the current second to provide an interesting display 



	if (objectServerID == "L-1"):	

		#check for validate request
		if (validate == "YES"):
			outgoingXMLData += Validate.buildValidateResponse("YES")
			outgoingXMLData += BuildResponse.buildFooter()

			return outgoingXMLData

		output = subprocess.check_output(["date", "+%s"])
		ledoutput = int(output)%7



		responseData = "%i" % ledoutput


		outgoingXMLData += BuildResponse.buildResponse(responseData)


	else:

		# invalid RaspiConnect Code
		outgoingXMLData += Validate.buildValidateResponse("NO")


	outgoingXMLData += BuildResponse.buildFooter()
	if (Config.debug()):
		print(outgoingXMLData)

	return outgoingXMLData
def Execute_Freq_Mod_LED(root):

    # find the interface object type

    objectServerID = root.find("./OBJECTSERVERID").text
    objectFlags = root.find("./OBJECTFLAGS").text

    validate = Validate.checkForValidate(root)

    if (Config.debug()):
        print "VALIDATE=%s" % validate

    outgoingXMLData = BuildResponse.buildHeader(root)

    if (Config.debug()):
        print("objectServerID = %s" % objectServerID)

# we have the objectServerID so now we can choose the correct
# program

# L-1 sends back the current second to provide an interesting display

    if (objectServerID == "BL-1"):

        #check for validate request
        if (validate == "YES"):
            outgoingXMLData += Validate.buildValidateResponse("YES")
            outgoingXMLData += BuildResponse.buildFooter()

            return outgoingXMLData

        output = subprocess.check_output(["uptime", ""])
        list = output.split("average:")
        list2 = list[1].split(",")
        if (Config.debug()):
            print list2
            print list2[0]
        element = list2[0]

        FMOutput = 1 / (float(element) * 4.0 + 0.01)

        responseData = "%3.2f, %3.2f, %s" % (FMOutput, float(element),
                                             "CPU Load")

        outgoingXMLData += BuildResponse.buildResponse(responseData)

    else:

        # invalid RaspiConnect Code
        outgoingXMLData += Validate.buildValidateResponse("NO")

    outgoingXMLData += BuildResponse.buildFooter()
    if (Config.debug()):
        print outgoingXMLData

    return outgoingXMLData
예제 #8
0
def Execute_BarMeter(root):

      # find the interface object type


        objectServerID = root.find("./OBJECTSERVERID").text
        objectID = root.find("./OBJECTID").text

        if (Config.debug()):
        	print("objectServerID = %s" % objectServerID)

        validate = Validate.checkForValidate(root)

        if (Config.debug()):
        	print "VALIDATE=%s" % validate

        outgoingXMLData = BuildResponse.buildHeader(root)


	# we have the objectServerID so now we can choose the correct
	# program

	# BR-1 sends back the power supply voltage 


	# BR-1
	if (objectServerID == "BR-1"):	


                #check for validate request
                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()

                        return outgoingXMLData

		import random
        	if (Config.debug()):
	        	print random.randrange(0,9)
		voltage = 10.0 + (random.randrange(0,9)-10)/10.0
		responseData = "%f" % voltage
                outgoingXMLData += BuildResponse.buildResponse(responseData)
        else:
                # invalid RaspiConnect Code
                outgoingXMLData += Validate.buildValidateResponse("NO")


        outgoingXMLData += BuildResponse.buildFooter()

        return outgoingXMLData




# End of ExecuteBarMeter.py
				
예제 #9
0
    def getExceptionsForAllPeople(self, filename):
        repository = Classes.Repository("localhost", 27017)
        repository.add(filename)
        exceptionMessages = []

        for person in repository.getPeople():
            try:
                Validate.birthBeforeDeath(person)
            except Exceptions.PersonException as e:
                exceptionMessages.append(e.message)

        return exceptionMessages
def Execute_Server_Status(root):

        # find the interface object type

        objectServerID = root.find("./OBJECTSERVERID").text
        objectFlags = root.find("./OBJECTFLAGS").text

        validate = Validate.checkForValidate(root)

        if (Config.debug()):
        	print "VALIDATE=%s" % validate

        outgoingXMLData = BuildResponse.buildHeader(root)


        if (Config.debug()):
        	print("objectServerID = %s" % objectServerID)

	# we have the objectServerID so now we can choose the correct
	# program



	if (objectServerID == "SS-1"):	

                #check for validate request
                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()

                        return outgoingXMLData




		responseData = "2"


                outgoingXMLData += BuildResponse.buildResponse(responseData)


	else:

                # invalid RaspiConnect Code
                outgoingXMLData += Validate.buildValidateResponse("NO")


        outgoingXMLData += BuildResponse.buildFooter()
        if (Config.debug()):
        	print outgoingXMLData

        return outgoingXMLData
예제 #11
0
def Execute_BarMeter(root):

      # find the interface object type


	objectServerID = root.find("./OBJECTSERVERID").text
	objectID = root.find("./OBJECTID").text

	if (Config.debug()):
		print("objectServerID = %s" % objectServerID)

	validate = Validate.checkForValidate(root)

	if (Config.debug()):
		print("VALIDATE=%s" % validate)

	outgoingXMLData = BuildResponse.buildHeader(root)


	# we have the objectServerID so now we can choose the correct
	# program

	# BR-1 sends back the power supply voltage 


	# BR-1
	if (objectServerID == "BR-1"):	


		#check for validate request
		if (validate == "YES"):
			outgoingXMLData += Validate.buildValidateResponse("YES")
			outgoingXMLData += BuildResponse.buildFooter()

			return outgoingXMLData

		import random
		if (Config.debug()):
			print(random.randrange(0,9))
		voltage = 10.0 + (random.randrange(0,9)-10)/10.0
		responseData = "%f" % voltage
		outgoingXMLData += BuildResponse.buildResponse(responseData)
	else:
		# invalid RaspiConnect Code
		outgoingXMLData += Validate.buildValidateResponse("NO")


	outgoingXMLData += BuildResponse.buildFooter()

	return outgoingXMLData
예제 #12
0
파일: STTools.py 프로젝트: thiagoki/Tdevel
def writeSet(documents,
             output,
             resultFileTag="a2",
             debug=False,
             task=2,
             validate=True,
             writeScores=False):
    from collections import defaultdict
    import shutil
    counts = defaultdict(int)

    while output.endswith("/"):
        output = output[:-1]
    if output.endswith(".tar.gz"):
        outdir = output + "-temp"
    else:
        outdir = output
    if os.path.exists(outdir):
        shutil.rmtree(outdir)

    if not validate:
        print "Warning! No validation."
    for doc in documents:
        if validate:
            if debug: print >> sys.stderr, "Validating", doc.id
            Validate.allValidate(doc, counts, task, verbose=debug)
        #doc.proteins.sort(cmp=compareOffsets)
        #doc.triggers.sort(cmp=compareOffsets)
        if debug: print >> sys.stderr, "Writing", doc.id
        write(doc.id,
              outdir,
              doc.proteins,
              doc.triggers,
              doc.events,
              doc.relations,
              resultFileTag,
              counts,
              task=task,
              writeScores=writeScores)
        # Write text file
        #out = open(os.path.join(outdir, str(doc.id) + ".txt"), "wt")
        out = codecs.open(os.path.join(outdir,
                                       str(doc.id) + ".txt"), "wt", "utf-8")
        out.write(doc.text)
        out.close()
    if output.endswith(".tar.gz"):
        package(outdir, output,
                ["a1", "txt", resultFileTag, resultFileTag + ".scores"])
        shutil.rmtree(outdir)
    print counts
예제 #13
0
def Execute_Single_LED(root):

    # find the interface object type

    objectServerID = root.find("./OBJECTSERVERID").text
    objectFlags = root.find("./OBJECTFLAGS").text

    validate = Validate.checkForValidate(root)

    if (Config.debug()):
        print "VALIDATE=%s" % validate

    outgoingXMLData = BuildResponse.buildHeader(root)

    if (Config.debug()):
        print("objectServerID = %s" % objectServerID)

# we have the objectServerID so now we can choose the correct
# program

# L-1 sends back the current second to provide an interesting display

    if (objectServerID == "L-1"):

        #check for validate request
        if (validate == "YES"):
            outgoingXMLData += Validate.buildValidateResponse("YES")
            outgoingXMLData += BuildResponse.buildFooter()

            return outgoingXMLData

        output = subprocess.check_output(["date", "+%s"])
        ledoutput = int(output) % 7

        responseData = "%i" % ledoutput

        outgoingXMLData += BuildResponse.buildResponse(responseData)

    else:

        # invalid RaspiConnect Code
        outgoingXMLData += Validate.buildValidateResponse("NO")

    outgoingXMLData += BuildResponse.buildFooter()
    if (Config.debug()):
        print outgoingXMLData

    return outgoingXMLData
예제 #14
0
def Execute_Text_And_Title(root):

    # find the interface object type

    objectServerID = root.find("./OBJECTSERVERID").text
    objectFlags = root.find("./OBJECTFLAGS").text

    validate = Validate.checkForValidate(root)

    if (Config.debug()):
        print "VALIDATE=%s" % validate

    outgoingXMLData = BuildResponse.buildHeader(root)

    if (Config.debug()):
        print("objectServerID = %s" % objectServerID)

# we have the objectServerID so now we can choose the correct
# program

    if (objectServerID == "LT-1"):

        #check for validate request
        if (validate == "YES"):
            outgoingXMLData += Validate.buildValidateResponse("YES")
            outgoingXMLData += BuildResponse.buildFooter()

            return outgoingXMLData

        output = subprocess.check_output(
            ["cat", "/sys/class/thermal/thermal_zone0/temp"])
        FMOutput = float(output) / 1000.0

        responseData = "%3.2f, %3.2f, %s" % (FMOutput, FMOutput,
                                             "CPU Temp (deg C)")

        outgoingXMLData += BuildResponse.buildResponse(responseData)

    else:

        # invalid RaspiConnect Code
        outgoingXMLData += Validate.buildValidateResponse("NO")

    outgoingXMLData += BuildResponse.buildFooter()
    if (Config.debug()):
        print outgoingXMLData

    return outgoingXMLData
예제 #15
0
def sweep_first():
    Net = Nets.Net1  #Net1 as defined in Nets.py has just on linear hidden layer

    m_fold = 2  #number of folds of full k_fold cross validations
    k_fold = 5
    nb_hidden = 50  #number of folds of the cross-validation
    nb_iters = 2500  #(max) number of iterations during training
    batch_sizes = [1, 5, 50, 316]  #size of the batches during training

    use_tol = True  #use the tolerance as stopping criterion or not. train_error is used, so inter_states = True is required
    inter_states = True  #compute the train and test errors every 25 iterations, print them and save them in err_array

    err_list = [
        0,
    ] * len(batch_sizes)

    for i_, batch_size in enumerate(batch_sizes):
        print('##### Testing batch size: {} #####'.format(batch_size))
        model_params = [size, nb_hidden]
        criterion = nn.CrossEntropyLoss()
        optimizer = torch.optim.SGD
        crossval_params = [
            m_fold, k_fold, nb_iters, batch_size, use_tol, inter_states
        ]
        #Apply crossvalidation
        trn_error, vldt_error, err_array = Validate.Cross_validation_mxk(
            Net, model_params, criterion, optimizer, train_input, train_target,
            *crossval_params)

        err_list[i_] = err_array

    np.save(os.path.join('arrays_and_images', 'first_err_list'), err_list)
예제 #16
0
    def readTable(self):
        print(
            "Which table would you like to read, chose from the list below or press Q to go back to home page"
        )
        print(
            "location, growth_equity_firms, vc_firms, portfolio_companies, sector, investment, partners"
        )
        user_in = input("Table: ")
        v = Validate.Validate(self.cnx)
        if user_in.lower() == "q":
            return
        while not v.validateInput(user_in, [
                "location", "growth_equity_firms", "vc_firms",
                "portfolio_companies", "sector", "investment", "partners"
        ]):
            print(
                "Invalid Input try again, chose from the list below or press Q to go back to home page"
            )
            print(
                "location, growth_equity_firms, vc_firms, portfolio_companies, sector, investment, partners"
            )
            user_in = input("Table: ")
            if user_in.lower() == "q":
                return

        c = self.cnx.cursor()
        sql = "select * from " + user_in
        c.execute(sql)
        for row in c.fetchall():
            print(row)
        print("\n")
        c.close()
예제 #17
0
파일: Local.py 프로젝트: windy54/PI_Connect
def handleFeedBackButtonRequest(validate):
  global lastFileCount
  
  #check for validate request
  # validate allows RasPiConnect to verify this object is here 
  
  outgoingXMLData = ""
  if (validate == "YES"):
     outgoingXMLData = Validate.buildValidateResponse("YES")
     outgoingXMLData += BuildResponse.buildFooter()
  else:

     # not validate request, so execute
     # note that python is in the main directory for this call, not the local directory
     # check this is not the first file to be copied
     fileCount = readFileCount()
     print "lastFileCount = %d" % lastFileCount
     if (lastFileCount == -1):
        lastFileCount = fileCount
        # make sure that a latest file exists - should use excpetions really!
        filename ="/home/pi/imageprocessing/capture-%06d.jpg" %lastFileCount
        subprocess.call("cp %s ~/RasPiConnectServer/static/latest.jpg" %filename, shell=True)
        subprocess.call("cp %s ~/RasPiConnectServer/static/previous.jpg" %filename, shell=True)     	                   	
     if(fileCount !=-1):
       if (lastFileCount < fileCount):
          lastFileCount+=1
     subprocess.call("mv ~/RasPiConnectServer/static/latest.jpg ~/RasPiConnectServer/static/previous.jpg", shell=True)
     filename ="/home/pi/imageprocessing/capture-%06d.jpg" %lastFileCount
     subprocess.call("cp %s ~/RasPiConnectServer/static/latest.jpg" %filename, shell=True)
     responseData = "Image number %s" %lastFileCount
 
     outgoingXMLData = BuildResponse.buildResponse(responseData)
     outgoingXMLData += BuildResponse.buildFooter()
  return outgoingXMLData
예제 #18
0
def sweep_third():
    Net = Nets.Net2  #Net1 as defined in Nets.py has just on linear hidden layer
    nb_hiddens = [5, 20, 100, 500]

    m_fold = 2  #number of folds of full k_fold cross validations
    k_fold = 5  #number of folds of the cross-validation
    nb_iters = 300  #(max) number of iterations during training
    batch_size = 5  #size of the batches during training
    use_tol = True  #use the tolerance as stopping criterion or not
    inter_states = True  #compute the train and test errors every 25 iterations, print them and save them in err_array

    crossval_params = [
        m_fold, k_fold, nb_iters, batch_size, use_tol, inter_states
    ]
    err_list = [
        0,
    ] * len(nb_hiddens)

    for i_, nb_hidden in enumerate(nb_hiddens):
        print('##### Testing number of hidden neurons: {} #####'.format(
            nb_hidden))
        model_params = [size, nb_hidden]
        criterion = nn.CrossEntropyLoss()
        optimizer = torch.optim.Adam

        #Apply crossvalidation
        trn_error, vldt_error, err_array = Validate.Cross_validation_mxk(
            Net, model_params, criterion, optimizer, train_input, train_target,
            *crossval_params)

        err_list[i_] = err_array

    np.save(os.path.join('arrays_and_images', 'third_err_list'), err_list)
예제 #19
0
def saveUpdate():
    con = None
    cursor = None
    try:
        con = cx_Oracle.connect("system/abc123")
        cursor = con.cursor()
        print("Connected.")

        try:
            rno = int(enRnoUpdate.get())

            if rno < 1:
                messagebox.showerror(
                    "Issue",
                    "Invalid input : Roll No, Enter positive integers only.")
                enRnoUpdate.delete(0, END)
                enRnoUpdate.focus()
                return

        except ValueError:
            messagebox.showerror(
                "Issue", "Invalid input : Roll No, Enter integers only.")
            enRnoUpdate.delete(0, END)
            enRnoUpdate.focus()
            return

        rname = enNameUpdate.get()

        if Validate.validate(rname) == False:
            messagebox.showerror("Issue", "Invalid input : Name")
            enRnoUpdate.delete(0, END)
            return

        sql = "update student set rname ='%s' where rno = %d"
        args = (rname, rno)
        cursor.execute(sql % args)
        con.commit()
        print(cursor.rowcount, " Updated")

        if cursor.rowcount == 0:
            messagebox.showerror("Issue", "Student record not found.")
        else:
            messagebox.showinfo("Issue",
                                "Student record successfully updated.")
            enRnoUpdate.delete(0, END)
            enRnoUpdate.focus()
            enNameUpdate.delete(0, END)

    except cx_Oracle.DatabaseError as e:
        print("Issue : " + str(e))
        messagebox.showerror("Issue", str(e))
        con.rollback()

    finally:
        if cursor is not None:
            cursor.close()
        if con is not None:
            con.close()
            print("Disconnect.")
예제 #20
0
def GetPhoneNumber(IsClear=False, regex=None):
    Print(Enum.EnterPhoneNumber if not IsClear else "")
    number = input()
    res = None

    if len(number) < 3 or len(number) > 50:
        PrintError(Enum.InvPhoneLen)
        return GetPhoneNumber(IsClear, regex)
    if regex == None:
        res = Validate.Number(number)
    else:
        res = Validate.Number(number, regex)

    if not res:
        PrintError(Enum.InvalidPhone)
        return GetPhoneNumber(IsClear, regex)
    return number
예제 #21
0
def GetCityName(IsClear=False, regex=None):
    Print(Enum.EnterCity if not IsClear else "")
    city = input()
    res = None

    if len(city) < 3 or len(city) > 50:
        PrintError(Enum.InvCityLen)
        return GetCityName(IsClear, regex)
    if regex == None:
        res = Validate.City(city)
    else:
        res = Validate.City(city, regex)

    if not res:
        PrintError(Enum.InvalidCity)
        return GetCityName(IsClear, regex)
    return city
예제 #22
0
def GetPersonName(IsClear=False, regex=None):
    Print(Enum.EnterName if not IsClear else "")
    name = input()
    res = None

    if len(name) < 3 or len(name) > 50:
        PrintError(Enum.InvNameLen)
        return GetPersonName(IsClear, regex)
    elif regex == None:
        res = Validate.Name(name)
    else:
        res = Validate.Name(name, regex)

    if not res:
        PrintError(Enum.InvalidName)
        return GetPersonName(IsClear, regex)
    return name
예제 #23
0
def main():
    print(
        'Welcome to the Stevens Institute of Technology GEDCOM Family Tree Project - SSW555 2017'
    )

    repository = Classes.Repository("localhost", 27017, "test1.ged")

    Print.people(repository)
    Print.families(repository)
    Print.deadPeople(repository)
    Print.livingMarriedPeople(repository)
    Print.upcomingAnniversaries(repository)
    Print.recentDeadPeople(repository)
    Print.upcomingBirthdays(repository)

    Validate.people(repository)
    Validate.families(repository)
예제 #24
0
def saveAdd():
    con = None
    cursor = None
    try:
        con = cx_Oracle.connect("system/abc123")
        cursor = con.cursor()
        print("Connected.")

        try:
            rno = int(enRnoAdd.get())

            if rno < 1:
                messagebox.showerror(
                    "Issue",
                    "Invalid input : Roll No, Enter positive integers only.")
                enRnoAdd.delete(0, END)
                enRnoAdd.focus()
                return

        except ValueError:
            messagebox.showerror(
                "Issue", "Invalid input : Roll No, Enter integers only.")
            enRnoAdd.delete(0, END)
            enRnoAdd.focus()
            return

        rname = enNameAdd.get()

        if Validate.validate(rname) == False:
            messagebox.showerror("Issue", "Invalid input : Name")
            enNameAdd.delete(0, END)
            return

        sql = "insert into student values(%d,'%s')"
        args = (rno, rname)
        cursor.execute(sql % args)
        print(cursor.rowcount, "rows inserted.")
        if cursor.rowcount == 1:
            success()
            messagebox.showinfo("Issue", "Student record successfully added.")
            con.commit()
            enRnoAdd.delete(0, END)
            enRnoAdd.focus()
            enNameAdd.delete(0, END)
        else:
            messagebox.showerror("Issue", "Something went wrong.")

    except cx_Oracle.DatabaseError as e:
        print("Issue : " + str(e))
        messagebox.showerror("Issue", str(e))
        con.rollback()

    finally:
        if cursor is not None:
            cursor.close()
        if con is not None:
            con.close()
            print("Disconnect.")
예제 #25
0
def main(source_dir, out_file):
    with open(out_file, 'w') as f:
        for root, dirs, files in os.walk(source_dir):
            for d in dirs:
                print ("processing %s" % d)
                fold_dir = os.path.join(root, d)
                gold_dir = fold_dir.replace('source', 'Golden Wiki')
                res = Validate.main(fold_dir, gold_dir)
                f.write("%s\t%f\n" % (d, res))
예제 #26
0
def main(source_dir, out_file):
    with open(out_file, 'w') as f:
        for root, dirs, files in os.walk(source_dir):
            for d in dirs:
                print("processing %s" % d)
                fold_dir = os.path.join(root, d)
                gold_dir = fold_dir.replace('source', 'Golden Wiki')
                res = Validate.main(fold_dir, gold_dir)
                f.write("%s\t%f\n" % (d, res))
def Execute_Server_Status(root):

    # find the interface object type

    objectServerID = root.find("./OBJECTSERVERID").text
    objectFlags = root.find("./OBJECTFLAGS").text

    validate = Validate.checkForValidate(root)

    if (Config.debug()):
        print "VALIDATE=%s" % validate

    outgoingXMLData = BuildResponse.buildHeader(root)

    if (Config.debug()):
        print("objectServerID = %s" % objectServerID)

# we have the objectServerID so now we can choose the correct
# program

    if (objectServerID == "SS-1"):

        #check for validate request
        if (validate == "YES"):
            outgoingXMLData += Validate.buildValidateResponse("YES")
            outgoingXMLData += BuildResponse.buildFooter()

            return outgoingXMLData

        responseData = "2"

        outgoingXMLData += BuildResponse.buildResponse(responseData)

    else:

        # invalid RaspiConnect Code
        outgoingXMLData += Validate.buildValidateResponse("NO")

    outgoingXMLData += BuildResponse.buildFooter()
    if (Config.debug()):
        print outgoingXMLData

    return outgoingXMLData
예제 #28
0
def homePage(conn):
    print("Enter any of the following commands to interact with the database")
    print("Create, Read, Update, Delete")
    user_in = input("What would you like to do: ")
    v = Validate.Validate(conn)
    while not v.validateInput(user_in, ["Create", "Read", "Update", "Delete"]):
        print("Invalid input please select from the following:")
        print("Create, Read, Update, Delete")
        user_in = input("What would you like to do: ")

    return user_in
예제 #29
0
    def validateReadInputValue(self, in1, table, column, message):
        try:
            identifier = input(in1)
            v = Validate.Validate(self.cnx)
            while not v.validateExists(table, column, identifier, message):
                identifier = input(in1)
                if identifier.lower() == 'q':
                    return []
        except ValueError:
            print("Read failed, id was not valid")
            return []

        return [identifier]
예제 #30
0
파일: Local.py 프로젝트: windy54/PI_Connect
def handleImageRequest(validate, imageName):
	#check for validate request
	response=""
	if (validate == "YES"):
		response = Validate.buildValidateResponse("YES")
		response += BuildResponse.buildFooter()
		
	else:	
		responseData =buildImageResponse(imageName)
		response = BuildResponse.buildResponse(responseData)
		response += BuildResponse.buildFooter()
		
        if (Config.debug()):
		print response	
	return response
예제 #31
0
    def validateCreateInputValue(self, arr, table, column, message):
        try:
            identifier = input(arr[0])
            v = Validate.Validate(self.cnx)
            while not v.validateUnique(table, column, identifier, message):
                identifier = input(arr[0])
                if identifier == 'Q':
                    return []
        except ValueError:
            print("Cannot input a string as an ID, must be an int, try again")
            return []

        tempArr = [""] * len(arr)
        tempArr[0] = identifier
        for val in range(1, len(arr)):
            tempArr[val] = input(arr[val])

        return tempArr
예제 #32
0
    def validateUpdateInputValue(self, in1, in2, table, column, message):
        try:
            identifier = input(in1)
            v = Validate.Validate(self.cnx)
            while not v.validateExists(table, column, int(identifier),
                                       message):
                identifier = input(in1)
                if identifier.lower() == 'Q':
                    return []

            value = input(in2)
        except ValueError:
            print(
                "Update Failed!, Check inputs to see if they are the correct type"
            )
            return []

        return [value, identifier]
예제 #33
0
    def delegate(self):
        print(
            "What do you want to delete? Please chose from the following options, or press Q to go back:"
        )
        print(
            "Investment, Location, Partner, Growth Equity Firm, VC Firm, Portfolio Company, Sector"
        )
        user_in = input("Delete: ")
        if user_in.lower() == "q":
            return app.main(self.cnx)
        v = Validate.Validate(self.cnx)
        while not v.validateInput(user_in, [
                "Investment", "Location", "Partner", "Growth Equity Firm",
                "VC Firm", "Portfolio Company", "Sector"
        ]):
            print(
                "Invalid Input Please try again with the options below, or enter Q to go back"
            )
            print(
                "Investment, Location, Partner, Growth Equity Firm, VC Firm, Portfolio Company, Sector"
            )
            user_in = input("Delete: ")
            if user_in.lower() == "q":
                return app.main(self.cnx)

        user_in = user_in.lower()
        if user_in == "investment":
            return self.delInvestment()
        elif user_in == "location":
            return self.delLocation()
        elif user_in == "partner":
            return self.delPartner()
        elif user_in == "growth equity firm":
            return self.delGrowthEquity()
        elif user_in == "vc firm":
            return self.delVC()
        elif user_in == "portfolio company":
            return self.delPortfolio()
        elif user_in == "sector":
            return self.delSector()
예제 #34
0
    def delegate(self):
        print(
            "What do you want to read? Please chose from the following options, or press Q to go back:"
        )
        print(
            "Table, Portfolios by Sector, Investments by VC Firm, Investments by GE Firm,"
            " Partners at Firm, Firms in Location")
        user_in = input("Read: ")
        if user_in.lower() == "q":
            return app.main(self.cnx)
        v = Validate.Validate(self.cnx)
        while not v.validateInput(user_in, [
                "Table", "Portfolios by Sector", "Investments by VC Firm",
                "Investments by GE Firm", "Partners at Firm",
                "Firms in Location"
        ]):
            print(
                "Invalid Input Please try again with the options below, or enter Q to go back"
            )
            print(
                "Table, Portfolios by Sector, Investments by VC Firm, Investments by GE Firm,"
                " Partners at Firm, Firms in Location")
            user_in = input("Create: ")
            if user_in.lower() == "q":
                return app.main(self.cnx)

        user_in = user_in.lower()
        if user_in == "table":
            return self.readTable()
        elif user_in == "portfolios by sector":
            return self.getSectorPortfolioCo()
        elif user_in == "investments by vc firm":
            return self.getInvestmentsByVCFirm()
        elif user_in == "investments by ge firm":
            return self.getInvestmentsByGEFirm()
        elif user_in == "partners at firm":
            return self.getPartnersForVCFirm()
        elif user_in == "firms in location":
            return self.getFirmsInLocation()
예제 #35
0
    def ISTransactionAuthorized(self, couponCode):
        global productName, productId, resource_id
        isCouponValid = False
        json_obj = Validate.validateCoupon(couponCode, resource_id)
        #json_obj = Producer.validateCoupon(couponCode)
        if (json_obj["CouponStatus"]):
            print "Coupon Accepted"
            productName = json_obj["CouponStatus"][0]["item"]
            cf = SafeConfigParser()
            cf.read('config.cfg')
            for section_name in cf.sections():
                for name, value in cf.items(section_name):
                    if (value == productName):
                        print "Item found"
                        productId = name
                        print productId
                        break

            isCouponValid = True
        else:
            isCouponValid = False
        return isCouponValid
 def ISTransactionAuthorized(self,couponCode):
     global productName, productId, resource_id
     isCouponValid = False
     json_obj = Validate.validateCoupon(couponCode,resource_id)
     #json_obj = Producer.validateCoupon(couponCode)
     if(json_obj["CouponStatus"]):
         print "Coupon Accepted"
         productName = json_obj["CouponStatus"][0]["item"]
         cf = SafeConfigParser()
         cf.read('config.cfg')
         for section_name in cf.sections():
             for name, value in cf.items(section_name):
                 if(value == productName):
                     print "Item found"
                     productId = name
                     print productId
                     break
                 
         isCouponValid = True
     else:
         isCouponValid = False
     return isCouponValid
예제 #37
0
    def delegate(self):
        print(
            "What do you want to update? Please chose from the following options, or enter Q to go back:"
        )
        print(
            "Sector Fund, Investment Amount, Investment Series, Partner Firm, Partner Contact"
        )
        user_in = input("Update: ")
        if user_in.lower() == 'q':
            return app.main(self.cnx)
        v = Validate.Validate(self.cnx)
        while not v.validateInput(user_in, [
                "Sector Fund", "Investment Amount", "Investment Series",
                "Partner Firm", "Partner Contact"
        ]):
            print(
                "Invalid Input Please try again with the options below, or enter Q to go back"
            )
            print(
                "Sector Fund, Investment Amount, Investment Series, Partner Firm, Partner Contact"
            )
            user_in = input("Update: ")
            if user_in.lower() == "q":
                return app.main(self.cnx)

        user_in = user_in.lower()
        if user_in == "sector fund":
            return self.updateSector()
        elif user_in == "investment amount":
            return self.updateInvestmentAmount()
        elif user_in == "investment series":
            return self.updateInvestmentSeries()
        elif user_in == "partner firm":
            return self.updatePartnerFirm()
        elif user_in == "partner contact":
            return self.updatePartnerContact()
예제 #38
0
def ExecuteUserObjects(objectType, element):

	# Example Objects
	global port25
	global port24
	global FMOutput

	# fetch information from XML for use in user elements

	#objectServerID is the RasPiConnect ID from the RasPiConnect App

        objectServerID = element.find("./OBJECTSERVERID").text
        objectID = element.find("./OBJECTID").text

        if (Config.debug()):
        	print("objectServerID = %s" % objectServerID)
	# 
	# check to see if this is a Validate request
	#
        validate = Validate.checkForValidate(element)

        if (Config.debug()):
        	print "VALIDATE=%s" % validate

        
	# Build the header for the response

	outgoingXMLData = BuildResponse.buildHeader(element)


	# objects are split up by object types by Interface Constants
	#
	#
	#
	# search for matches to object Type 

	# object Type match
	print("+++++++++++OBJECTTYPE %i" % objectType)
	if (objectType == ACTION_BUTTON_UITYPE):

		if (Config.debug()):
			print "ACTION_BUTTON_UTYPE of %s found" % objectServerID

		# B-2 - play a beep on the Raspberry Pi
		if (objectServerID == "B-2"):	

                	#check for validate request
			# validate allows RasPiConnect to verify this object is here 
                	if (validate == "YES"):
                        	outgoingXMLData += Validate.buildValidateResponse("YES")
                        	outgoingXMLData += BuildResponse.buildFooter()
                        	return outgoingXMLData

			# not validate request, so execute

			# note that python is in the main directory for this call, not the local directory

			output = subprocess.call(["aplay", "sounds/match1.wav"])
			
			responseData = "OK"
                	outgoingXMLData += BuildResponse.buildResponse(responseData)
      			outgoingXMLData += BuildResponse.buildFooter()
                	return outgoingXMLData
	if (objectType == TEXT_DISPLAY_UITYPE):
		
        	if (objectServerID == "LT-1"):	

        	        #check for validate request
                	if (validate == "YES"):
                        	outgoingXMLData += Validate.buildValidateResponse("YES")
                 	        outgoingXMLData += BuildResponse.buildFooter()

                        	return outgoingXMLData

#			output = subprocess.check_output(["cat", "/sys/class/thermal/thermal_zone0/temp"])
			output = board_revision
			FMOutput += 1000.0
			
			print "VERSION++++++++++++++=%s" % output

			responseData = "%3.2f, %3.2f, %s" % (FMOutput,FMOutput, output,)

	                outgoingXMLData += BuildResponse.buildResponse(responseData)
     			outgoingXMLData += BuildResponse.buildFooter()
                	return outgoingXMLData
                	
        	if (objectServerID == "LT-2"):	

        	        #check for validate request
                	if (validate == "YES"):
                        	outgoingXMLData += Validate.buildValidateResponse("YES")
                 	        outgoingXMLData += BuildResponse.buildFooter()

                        	return outgoingXMLData

#			output = subprocess.check_output(["cat", "/sys/class/thermal/thermal_zone0/temp"])
			output = board_revision
			FMOutput = 2222.0

			
                        print "VERSION---------=%s" % output



			responseData = "%3.2f, %3.2f, %s" % (output,output, "RPI Version")

	                outgoingXMLData += BuildResponse.buildResponse(responseData)
     			outgoingXMLData += BuildResponse.buildFooter()
                	return outgoingXMLData

	if (objectType == SINGLE_LED_DISPLAY ):

        	        #check for validate request
                	if (validate == "YES"):
                        	outgoingXMLData += Validate.buildValidateResponse("YES")
                 	        outgoingXMLData += BuildResponse.buildFooter()
                        	return outgoingXMLData
			if(port25):
			  wiringpi.digitalWrite(25, 0)      # switch on an led
			  port25=False
			  ledColour = 5
			  print "Led off"
			else:
			  wiringpi.digitalWrite(25, 1)      # switch on an led
			  port25=True
			  ledColour=2
			  print "Led on"
			
			responseData = "%i" % (ledColour)


	                outgoingXMLData += BuildResponse.buildResponse(responseData)
     			outgoingXMLData += BuildResponse.buildFooter()
                	return outgoingXMLData	
	if (objectType == FEEDBACK_ACTION_BUTTON_UITYPE):
        	        #check for validate request
                	if (validate == "YES"):
                        	outgoingXMLData += Validate.buildValidateResponse("YES")
                 	        outgoingXMLData += BuildResponse.buildFooter()
                        	return outgoingXMLData
			if(port24):
			  wiringpi.digitalWrite(24,0)      # switch on an led
			  port24=False
			  responseData = "Port 24 Led off"
			else:
			  wiringpi.digitalWrite(24, 1)      # switch on an led
			  port24=True
			  responseData = "port 24 Led on"
			
	                outgoingXMLData += BuildResponse.buildResponse(responseData)
     			outgoingXMLData += BuildResponse.buildFooter()
                	return outgoingXMLData
	if( objectType ==VOLTMETER_UITYPE ):
        	        #check for validate request
                	if (validate == "YES"):
                        	outgoingXMLData += Validate.buildValidateResponse("YES")
                 	        outgoingXMLData += BuildResponse.buildFooter()
                        	return outgoingXMLData

			adc_value = (get_adc(0))  # read ADC voltage 
			if adc_value > 511:                 # above half-way on the pot
            			wiringpi.digitalWrite(17, 0)    # motor spins one way
		                pwm = (adc_value - 511) * 2 -1
        		else:                               # below half-way on the pot
            			wiringpi.digitalWrite(17, 1)    # motor spins the other way
            			pwm = adc_value * 2 + 1

        		wiringpi.pwmWrite(18, pwm)          # send PWM value to port 18

			responseData = "%i" % (adc_value)
	                outgoingXMLData += BuildResponse.buildResponse(responseData)
     			outgoingXMLData += BuildResponse.buildFooter()
                	return outgoingXMLData	
	
	else:
		return ""
	# returning a zero length string tells the server that you have not matched 
	# the object and server 
	return ""
예제 #39
0
def Execute_Meter(root):

      # find the interface object type


	objectServerID = root.find("./OBJECTSERVERID").text
	objectID = root.find("./OBJECTID").text

	if (Config.debug()):
		print(("objectServerID = %s" % objectServerID))

	validate = Validate.checkForValidate(root)

	if (Config.debug()):
		print("VALIDATE=%s" % validate)

	outgoingXMLData = BuildResponse.buildHeader(root)


	# we have the objectServerID so now we can choose the correct
	# program

	# M-1 sends back the power supply voltage 
	# M-2 sends back the number of processes running on the Raspberry Pi 


	# M-1
	if (objectServerID == "M-1"):	


		#check for validate request
		if (validate == "YES"):
			outgoingXMLData += Validate.buildValidateResponse("YES")
			outgoingXMLData += BuildResponse.buildFooter()

			return outgoingXMLData

		import random
		if (Config.debug()):
			print(random.randrange(0,9))
		voltage = 5.0 + (random.randrange(0,9)-5)/10.0
		responseData = "%f" % voltage
		outgoingXMLData += BuildResponse.buildResponse(responseData)

	# M-2
	elif (objectServerID == "M-2"):	

		#check for validate request
		if (validate == "YES"):
			outgoingXMLData += Validate.buildValidateResponse("YES")
			outgoingXMLData += BuildResponse.buildFooter()

			return outgoingXMLData

		p1 = subprocess.Popen(['ps', 'xaf'], stdout=subprocess.PIPE)
		p3 = subprocess.Popen(['wc', '-l'], stdin=p1.stdout,stdout=subprocess.PIPE)
		p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p3 exits.
		output = p3.communicate()[0]
		numberofprocesses = int(output)
		responseData = "%i" % numberofprocesses
		outgoingXMLData += BuildResponse.buildResponse(responseData)
	else:
		# invalid RaspiConnect Code
		outgoingXMLData += Validate.buildValidateResponse("NO")


	outgoingXMLData += BuildResponse.buildFooter()

	return outgoingXMLData
def Execute_Freq_Mod_LED(root):

        # find the interface object type

        objectServerID = root.find("./OBJECTSERVERID").text
        objectFlags = root.find("./OBJECTFLAGS").text

        validate = Validate.checkForValidate(root)

        if (Config.debug()):
        	print "VALIDATE=%s" % validate

        outgoingXMLData = BuildResponse.buildHeader(root)


        if (Config.debug()):
        	print("objectServerID = %s" % objectServerID)

	# we have the objectServerID so now we can choose the correct
	# program

	# L-1 sends back the current second to provide an interesting display 



	if (objectServerID == "BL-1"):	

                #check for validate request
                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()

                        return outgoingXMLData

		output = subprocess.check_output(["uptime", ""])
		list = output.split("average:")
		list2 = list[1].split(",")
        	if (Config.debug()):
			print list2
			print list2[0]	
		element = list2[0]

		FMOutput = 1/(float(element)*4.0+0.01)



		responseData = "%3.2f, %3.2f, %s" % (FMOutput, float(element),"CPU Load")


                outgoingXMLData += BuildResponse.buildResponse(responseData)


	else:

                # invalid RaspiConnect Code
                outgoingXMLData += Validate.buildValidateResponse("NO")


        outgoingXMLData += BuildResponse.buildFooter()
        if (Config.debug()):
        	print outgoingXMLData

        return outgoingXMLData
예제 #41
0
def ExecuteUserObjects(objectType, element):

	# Example Objects

	# fetch information from XML for use in user elements

	#objectServerID is the RasPiConnect ID from the RasPiConnect App

        objectServerID = element.find("./OBJECTSERVERID").text
        objectID = element.find("./OBJECTID").text

        if (Config.debug()):
        	print("objectServerID = %s" % objectServerID)
	# 
	# check to see if this is a Validate request
	#
        validate = Validate.checkForValidate(element)

        if (Config.debug()):
        	print "VALIDATE=%s" % validate

        
	# Build the header for the response

	outgoingXMLData = BuildResponse.buildHeader(element)


	# objects are split up by object types by Interface Constants
	#
	#
	#
	# search for matches to object Type 

	# object Type match
	if (objectType == ACTION_BUTTON_UITYPE):

		if (Config.debug()):
			print "ACTION_BUTTON_UTYPE of %s found" % objectServerID

		# B-2 - play a beep on the Raspberry Pi
		if (objectServerID == "B-2"):	

                	#check for validate request
			# validate allows RasPiConnect to verify this object is here 
                	if (validate == "YES"):
                        	outgoingXMLData += Validate.buildValidateResponse("YES")
                        	outgoingXMLData += BuildResponse.buildFooter()
                        	return outgoingXMLData

			# not validate request, so execute

			# note that python is in the main directory for this call, not the local directory

			output = subprocess.call(["aplay", "sounds/match1.wav"])
			
			responseData = "OK"
                	outgoingXMLData += BuildResponse.buildResponse(responseData)
      			outgoingXMLData += BuildResponse.buildFooter()
                	return outgoingXMLData
		


	else:
		return ""
	# returning a zero length string tells the server that you have not matched 
	# the object and server 
	return ""
예제 #42
0
파일: Local.py 프로젝트: windy54/legoRobot
def ExecuteUserObjects(objectType, element):

    global pictureFileStatus
    # Example Objects

    # fetch information from XML for use in user elements

    #objectServerID is the RasPiConnect ID from the RasPiConnect App

    objectServerID = element.find("./OBJECTSERVERID").text
    objectID       = element.find("./OBJECTID").text
    objectAction   = element.find("./OBJECTACTION").text
    objectName     = element.find("./OBJECTNAME").text

    if (Config.debug()):
        print("objectServerID = %s" % objectServerID)
    # 
    # check to see if this is a Validate request
    #
    validate = Validate.checkForValidate(element)

    if (Config.debug()):
        print "VALIDATE=%s" % validate

        
    # Build the header for the response

    outgoingXMLData = BuildResponse.buildHeader(element)

    #
    #
    
    if objectAction=="SINGLEPUSH":
        
        if (objectServerID == "B-1"):
                # stop
                #check for validate request
                # validate allows RasPiConnect to verify this object is here 

                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData

                # not validate request, so execute
                #
                # Execute your code
                #
                #
                lego.stop()
                responseData = "OK" ## send an OK back to the App
                # Done with your code
                #
                #

                outgoingXMLData += BuildResponse.buildResponse(responseData)
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

        elif (objectServerID == "B-4"): 

                # left
                #check for validate request
                # validate allows RasPiConnect to verify this object is here 

                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData

                # not validate request, so execute

                lego.turnLeft()
                responseData = "OK" ## send an OK back to the App
                #
                #
                # Done with your code

                outgoingXMLData += BuildResponse.buildResponse(responseData)
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData
                


        elif (objectServerID == "B-5"):
                # right
                #check for validate request
                # validate allows RasPiConnect to verify this object is here 

                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData

                # not validate request, so execute
                #
                # Execute your code
                #
                #
                lego.turnRight()
                responseData = "OK" ## send an OK back to the App
                # Done with your code
                #
                #

                outgoingXMLData += BuildResponse.buildResponse(responseData)
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

        elif (objectServerID == "B-6"):
                # forwards
                #check for validate request
                # validate allows RasPiConnect to verify this object is here 

                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData

                # not validate request, so execute

                lego.moveForwards()
                responseData = "OK" ## send an OK back to the App
                # Done with your code
                #
                #

                outgoingXMLData += BuildResponse.buildResponse(responseData)
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

                
        elif (objectServerID == "B-7"):
                # backwards
                #check for validate request
                # validate allows RasPiConnect to verify this object is here 

                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData

                # not validate request, so execute

                lego.moveBackwards()
                responseData = "OK" ## send an OK back to the App
                # Done with your code
                #
                #

                outgoingXMLData += BuildResponse.buildResponse(responseData)
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

                
        elif (objectServerID == "B-8"):
                # shutdown
                #check for validate request
                # validate allows RasPiConnect to verify this object is here 

                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData

                # not validate request, so execute
                #
                # Execute your code
                #
                #
                os.system("sudo shutdown -h now")
                responseData = "OK" ## send an OK back to the App
                # Done with your code
                #
                #

                outgoingXMLData += BuildResponse.buildResponse(responseData)
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

        elif (objectServerID == "B-9"):
                #calibrate
                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData
                
                responseData = "exit"
                print "exit "
                sys.exit()

                outgoingXMLData += BuildResponse.buildResponse(responseData)
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData  

        elif (objectServerID == "B-10"):
                #calibrate
                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData
                
                responseData = "ok"
                lego.turn(90)

                outgoingXMLData += BuildResponse.buildResponse(responseData)
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData
        elif (objectServerID == "FB-1"):
            #calibrate
            if (validate == "YES"):
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData
        
            responseData = lego.calibrate()

            outgoingXMLData += BuildResponse.buildResponse(responseData)
            outgoingXMLData += BuildResponse.buildFooter()
            return outgoingXMLData


        else:
                # returning a zero length string tells the server that you have not matched 
                # the object and server 
                print "unknown objectServerID ",objectServerID
                #lego.stop()
                                
    elif (objectServerID == "LT-1"):
        #text box range
        if (validate == "YES"):
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData
        range = lego.getRange()
        responseData = "%d" % (range)

        outgoingXMLData += BuildResponse.buildResponse(responseData)
        outgoingXMLData += BuildResponse.buildFooter()
        return outgoingXMLData
        
    elif (objectServerID == "LT-2"):
        #text box heading
        if (validate == "YES"):
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData
        heading = lego.getHeading()
        responseData = "%d" % (heading,)

        outgoingXMLData += BuildResponse.buildResponse(responseData)
        outgoingXMLData += BuildResponse.buildFooter()
        return outgoingXMLData


    elif (objectServerID == "SL-1"):
        #adjust speed
        if (validate == "YES"):
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData
        
        commandResponse = objectAction
        motorSpeed = float(commandResponse) * 2.5
        if  motorSpeed > 250:
            motorSpeed = 250
        newValue =  float(lego.setSpeed( int(motorSpeed) ) ) / 2.5 # integer 0 to 100
        responseData = "%d" % (newValue)

        outgoingXMLData += BuildResponse.buildResponse(responseData)
        outgoingXMLData += BuildResponse.buildFooter()
        return outgoingXMLData
    elif (objectServerID == "W-2"):
    
        #check for validate request
        if (validate == "YES"):
            outgoingXMLData += Validate.buildValidateResponse("YES")
            outgoingXMLData += BuildResponse.buildFooter()

            return outgoingXMLData
            
        # normal response requested 

        imageName = "legoraw.jpg"
        if pictureFileStatus == 0:
            imageName = "RovioImage.jpg"
            useCamera.takePicture("legoraw1.jpg")
            pictureFileStatus = 1
        elif pictureFileStatus == 1:
            imageName = "legoraw1.jpg"
            useCamera.takePicture("legoraw2.jpg")
            pictureFileStatus = 2
        else:
            imageName = "legoraw2.jpg"
            useCamera.takePicture("legoraw1.jpg")
            pictureFileStatus = 1
        

        responseData = "<html><head>"
        responseData += "<title></title><style>body,html,iframe{margin:0;padding:0;}</style>"
        responseData += "</head>"
        
        responseData += "<body><img src=\""
        responseData += Config.localURL() 
        responseData += "static/"
        responseData += imageName
        responseData += "\" type=\"jpg\" width=\"300\" height=\"300\">"
        responseData += "<BR>Picture<BR>"

        responseData +="</body>"
        
        responseData += "</html>"
    
        
        outgoingXMLData += BuildResponse.buildResponse(responseData)
        outgoingXMLData += BuildResponse.buildFooter()
        if (Config.debug()):
            print outgoingXMLData

        return outgoingXMLData  

    else:
        # returning a zero length string tells the server that you have not matched 
        # the object and server 
        #lego.stop()
        return ""
예제 #43
0
def ExecuteUserObjects(objectType, element):

	#
	# Fetch information from XML for use in user elements
	# objectServerID:	Control Code
	# objectType:		Interface constant (*_UITYPE)
	# objectName:		Display Name of Control
	# objectID:			???
	# objectFlags:		???
	# objectAction:		???
	objectServerID = element.find("./OBJECTSERVERID").text
	#objectType = element.find("./OBJECTTYPE").text
	objectName = element.find("./OBJECTNAME").text
	objectID = element.find("./OBJECTID").text
	objectFlags = element.find("./OBJECTFLAGS").text
	objectAction = element.find("./OBJECTACTION").text

	if LocalDEBUG:
		print("=====================================")
		print("objectServerID\t= %s" % objectServerID)
		print("objectType\t= %s" % objectType)
		print("objectName\t= %s" % objectName)
		print("objectID\t= %s" % objectID)
		print("objectFlags\t= %s" % objectFlags)
		print("objectAction\t= %s" % objectAction)

	#
	# Check if this is a Validate request
	#
	validate = Validate.checkForValidate(element)
	bValidate = False
	if (validate == "YES"):
		bValidate = True

	if LocalDEBUG:
		print("VALIDATE\t= %s" % validate)

	#
	# Run handler and get the response; update activity for the handler
	#
	responseData = ""
	handlers = ObjectServerHandlers.handlers_for_address(objectServerID)
	for handler in handlers:
		if len(handler.args) > 0:
			handler.args[1] = objectName
			handler.args[2] = objectAction
			responseData = handler.callback(handler.args, bValidate)
			ObjectServerHandlers.activity_for_handler(handler.callback)

	#
	# Update the activity metric for all handlers
	#
	ObjectServerHandlers.update_handlers_activity()
	
	if LocalDEBUG:
		print("-------------------------------------")
		for addr, handlers in ObjectServerHandlers._map.items():
			for handler in handlers:
				print("{:8s}()\t: {:4.2f}".format(handler.callback.__name__, ObjectServerHandlers.activity_metric[handler.callback.__name__]))

	# Return a zero length string when no match for the objectServerID was found	
	if len(responseData) == 0:
		return ""
	
	#	
	# Build the header
	#
	outgoingXMLData = BuildResponse.buildHeader(element)

	#
	# Build a valid response
	#			
	if responseData == "VALIDATED":
		# Build VALIDATED response 
		outgoingXMLData += Validate.buildValidateResponse("YES")
	
	else:	
		# Build respose 
		outgoingXMLData += BuildResponse.buildResponse(responseData)

	#
	# Build footer
	#	
	outgoingXMLData += BuildResponse.buildFooter()
	#if LocalDEBUG:
	#	print(outgoingXMLData)

	#
	# Return XML response
	#
	return outgoingXMLData
예제 #44
0
#!/usr/bin/env python

import regrmdup, rawData, sys, MTIS, Validate

validate, mtis = False, False

if validate:
	Validate.myValidate(sys.argv).doBatch()
elif mtis:
	# build MTIS data
	MTIS.myMTIS(sys.argv).matrixBuilder()
else:
	# compute thesis data
	prepare = rawData.splitRawData(sys.argv)
	prepare.doBatch()
	regrmdup.prepross(prepare.splitedRawData()).doBatch()
def ExecuteUserObjects(objectType, element):

	# Example Objects

	# fetch information from XML for use in user elements

	#objectServerID is the RasPiConnect ID from the RasPiConnect App

        objectServerID = element.find("./OBJECTSERVERID").text
        objectID = element.find("./OBJECTID").text
        objectAction = element.find("./OBJECTACTION").text
        objectName = element.find("./OBJECTNAME").text

        if (Config.debug()):
        	print("objectServerID = %s" % objectServerID)
	# 
	# check to see if this is a Validate request
	#
        validate = Validate.checkForValidate(element)

        if (Config.debug()):
        	print "VALIDATE=%s" % validate

        
	# Build the header for the response

	outgoingXMLData = BuildResponse.buildHeader(element)

	#
	# W-10 Main plan  Web page screen 
	if (objectServerID == "W-10"):	

               	#check for validate request
		# validate allows RasPiConnect to verify this object is here 

               	if (validate == "YES"):
                       	outgoingXMLData += Validate.buildValidateResponse("YES")
                       	outgoingXMLData += BuildResponse.buildFooter()
                       	return outgoingXMLData

		# not validate request, so execute

		# note that python is in the main directory for this call, not the local directory

		# read an HTML template into aw string

		
		responseData = "<html><head>"
              	responseData += "<title></title><style>body,html,iframe{margin:0;padding:0;}"
		tempString = ""
		try:
       			f = open("/home/pi/RasPiConnectServer/Templates/W-1b.txt", "r")
              		tempString = f.read()
               		f.close()
		except IOError as e:
			tempString = ""	

		responseData += tempString
 		responseData += "</style>"

		#responseData += "<META HTTP-EQUIV='CACHE-CONTROL' CONTENT='NO-CACHE'>"
             	responseData += "</head>"
		# read in the rest of the css definitions 

              	responseData += "<body>"

         	responseData += "<div style='position: relative; left: 0; top: 0;'>\n"
               	responseData += "<img src='http://rfw.wardner.com:9600/static/mainplanfull.png' style='position: relative; top: 0; left: 0;'/>\n"

		# read in the rest of the objects
		tempString = ""
		try:
       			f = open("/home/pi/RasPiConnectServer/Templates/W-1a.txt", "r")
              		tempString = f.read()
               		f.close()
		except IOError as e:
			tempString = ""	

		responseData += tempString


               	responseData += "</div>"


               	responseData +="</body>"

              	responseData += "</html>"

		print "responseData =", responseData

               	outgoingXMLData += BuildResponse.buildResponse(responseData)
      		outgoingXMLData += BuildResponse.buildFooter()
               	return outgoingXMLData
		

	#
	# BTL-1 Bubble Log
	if (objectServerID == "BTL-1"):	

               	#check for validate request
		# validate allows RasPiConnect to verify this object is here 

               	if (validate == "YES"):
                       	outgoingXMLData += Validate.buildValidateResponse("YES")
                       	outgoingXMLData += BuildResponse.buildFooter()
                       	return outgoingXMLData

		responseData =""
		# not validate request, so execute

		# note that python is in the main directory for this call, not the local directory
		try:
       			f = open("/home/pi/BeaconAir/state/bubblelog.txt", "r")
              		tempString = f.read()
              		f.close()
			os.remove("/home/pi/BeaconAir/state/bubblelog.txt")
		except IOError as e:
			tempString = ""	

		responseData = tempString


		print "responseData =", responseData

               	outgoingXMLData += BuildResponse.buildResponse(responseData)
      		outgoingXMLData += BuildResponse.buildFooter()
               	return outgoingXMLData
		


	# DSPL-1 Dynamic Spark Line event driven 
	if (objectServerID == "DSPL-1"):	

               	#check for validate request
		# validate allows RasPiConnect to verify this object is here 

               	if (validate == "YES"):
                       	outgoingXMLData += Validate.buildValidateResponse("YES")
                       	outgoingXMLData += BuildResponse.buildFooter()
                       	return outgoingXMLData

		responseData =""
		# not validate request, so execute

		# note that python is in the main directory for this call, not the local directory
		try:
       			f = open("/home/pi/BeaconAir/state/distancejitter.txt", "r")
              		tempString = f.read()
              		f.close()
			os.remove("/home/pi/BeaconAir/state/distancejitter.txt")
		except IOError as e:
			tempString = ""	

		responseData = tempString


		print "responseData =", responseData

               	outgoingXMLData += BuildResponse.buildResponse(responseData)
      		outgoingXMLData += BuildResponse.buildFooter()
               	return outgoingXMLData
		
	# SLGL-1 - Beacon count
	if (objectServerID == "SLGL-1"):	

               	#check for validate request
		# validate allows RasPiConnect to verify this object is here 
                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData

                # normal response requested
		try:
        		f = open("/home/pi/BeaconAir/state/iBeaconCountGraph.txt", "r")
        		commandresponse = f.read()
        		f.close()	
		except IOError as e:
			commandresponse = "0^^0||No Data from BeaconAir^^"			

                outgoingXMLData += BuildResponse.buildResponse(commandresponse)


                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData	

	# SL-1 - Sensitivity in meters 
	if (objectServerID == "SL-1"):	

               	#check for validate request
		# validate allows RasPiConnect to verify this object is here 
                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData

                # normal response requested
		commandresponse = objectAction	
	
		if (float(commandresponse) < 0.15):
                	try:
       	                 	f = open("/home/pi/BeaconAir/state/distanceSensitivity.txt", "r")
       	                 	commandresponse = f.read()
       	                 	f.close()
       	         	except:
                        	commandresponse = "2.0"
	
    		f = open("/home/pi/BeaconAir/state/distanceSensitivity.txt", "w")
        	f.write(commandresponse)
        	f.close()
		status = sendCommandToBeaconAirAndWait("UPDATESENSITIVITIES")
		# Not LIVE values, just send "" back
		
		commandresponse = ""
		
                outgoingXMLData += BuildResponse.buildResponse(commandresponse)


                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData	

	# SL-2 - Brightness Sensitivity in meters 
	if (objectServerID == "SL-2"):	

               	#check for validate request
		# validate allows RasPiConnect to verify this object is here 
                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData

                # normal response requested
		commandresponse = objectAction	
		if (float(commandresponse) < 0.15):
                	try:
                        	f = open("/home/pi/BeaconAir/state/brightnessSensitivity.txt", "r")
                        	commandresponse = f.read()
                        	f.close()
                	except:
                        	commandresponse = "2.0" 

    		f = open("/home/pi/BeaconAir/state/brightnessSensitivity.txt", "w")
        	f.write(commandresponse)
        	f.close()
		status = sendCommandToBeaconAirAndWait("UPDATESENSITIVITIES")
		# Not LIVE values, just send "" back
		
		commandresponse = ""
		
                outgoingXMLData += BuildResponse.buildResponse(commandresponse)


                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData	

	# LT-1 - display beacon count 
	if (objectServerID == "LT-1"):	

               	#check for validate request
		# validate allows RasPiConnect to verify this object is here 
                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData

                # normal response requested
		
		try:
       			f = open("/home/pi/BeaconAir/state/beaconCount.txt", "r")
              		tempString = f.read()
               		f.close()
		except IOError as e:
			tempString = "no count"	
		
		commandresponse = tempString + ", "+ tempString + ", iBeacon Count "

 
		
                outgoingXMLData += BuildResponse.buildResponse(commandresponse)


                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData	


	# FB-5 -  turn beacon reception on / off 
	if (objectServerID == "FB-5"):	

               	#check for validate request
		# validate allows RasPiConnect to verify this object is here 
               	if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData

		# not validate request, so execute

                responseData = "XXX"
 

                if (objectName is None):
                        objectName = "XXX"

               	lowername = objectName.lower()


               	if (lowername == "enable beacons"):

			status = sendCommandToBeaconAirAndWait("BEACONON") 
                       	responseData = "disable beacons" 
                       	responseData = responseData.title()


               	elif (lowername == "disable beacons"):

			status = sendCommandToBeaconAirAndWait("BEACONOFF")
                       	responseData = "enable beacons" 
                       	responseData = responseData.title()


		 # defaults to on 
               	else:
			status = sendCommandToBeaconAirAndWait("BEACONON") 
                       	lowername = "disable beacons" 
                       	responseData = lowername.title()


               	outgoingXMLData += BuildResponse.buildResponse(responseData)
      		outgoingXMLData += BuildResponse.buildFooter()
               	return outgoingXMLData





	# FB-1 -  turns display beacons on or off
	if (objectServerID == "FB-1"):	

               	#check for validate request
		# validate allows RasPiConnect to verify this object is here 
               	if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData

		# not validate request, so execute

                responseData = "XXX"
 

                if (objectName is None):
                        objectName = "XXX"

               	lowername = objectName.lower()


               	if (lowername == "display beacons on"):

			status = sendCommandToBeaconAirAndWait("DISPLAYBEACONON") 
                       	responseData = "display beacons off" 
                       	responseData = responseData.title()


               	elif (lowername == "display beacons off"):

			status = sendCommandToBeaconAirAndWait("DISPLAYBEACONOFF")
                       	responseData = "display beacons on" 
                       	responseData = responseData.title()


		 # defaults to on 
               	else:
			status = sendCommandToBeaconAirAndWait("DISPLAYBEACONON") 
                       	lowername = "display beacons off" 
                       	responseData = lowername.title()


               	outgoingXMLData += BuildResponse.buildResponse(responseData)
      		outgoingXMLData += BuildResponse.buildFooter()
               	return outgoingXMLData


	# FB-4 -  turns display beacons on or off
	if (objectServerID == "FB-4"):	

               	#check for validate request
		# validate allows RasPiConnect to verify this object is here 
               	if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData

		# not validate request, so execute

                responseData = "XXX"
 

                if (objectName is None):
                        objectName = "XXX"

               	lowername = objectName.lower()


               	if (lowername == "display lights on"):

			status = sendCommandToBeaconAirAndWait("DISPLAYLIGHTSON") 
                       	responseData = "display beacons off" 
                       	responseData = responseData.title()


               	elif (lowername == "display lights off"):

			status = sendCommandToBeaconAirAndWait("DISPLAYLIGHTSOFF")
                       	responseData = "display beacons on" 
                       	responseData = responseData.title()


		 # defaults to on 
               	else:
			status = sendCommandToBeaconAirAndWait("DISPLAYLIGHTSON") 
                       	lowername = "display lights off" 
                       	responseData = lowername.title()


               	outgoingXMLData += BuildResponse.buildResponse(responseData)
      		outgoingXMLData += BuildResponse.buildFooter()
               	return outgoingXMLData


	# FB-2 -  turns display beacons on or off
	if (objectServerID == "FB-2"):	

               	#check for validate request
		# validate allows RasPiConnect to verify this object is here 
               	if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData

		# not validate request, so execute

                responseData = "XXX"
 

                if (objectName is None):
                        objectName = "XXX"

               	lowername = objectName.lower()


               	if (lowername == "all lights on"):

			status = sendCommandToBeaconAirAndWait("ALLLIGHTSON") 
                       	responseData = "all lights off" 
                       	responseData = responseData.title()


               	elif (lowername == "all lights off"):

			status = sendCommandToBeaconAirAndWait("ALLLIGHTSOFF")
                       	responseData = "all lights on" 
                       	responseData = responseData.title()


		 # defaults to on 
               	else:
			status = sendCommandToBeaconAirAndWait("ALLLIGHTSON") 
                       	lowername = "all lights off" 
                       	responseData = lowername.title()


               	outgoingXMLData += BuildResponse.buildResponse(responseData)
      		outgoingXMLData += BuildResponse.buildFooter()
               	return outgoingXMLData



	else:
		return ""
	# returning a zero length string tells the server that you have not matched 
	# the object and server 
	return ""
예제 #46
0
파일: Local.py 프로젝트: windy54/PI_Connect
def handleCameraStatusUpdate(validate):
  
  global lastFileCount
  
  #check for validate request
  outgoingXMLData =""	
  if (validate == "YES"):
	outgoingXMLData = Validate.buildValidateResponse("YES")
	outgoingXMLData += BuildResponse.buildFooter()
  else:	
	responseData = ""
	fileCount =  readFileCount()			

	# read an HTML template into aw string		
	with open ("./Templates/camera.html", "r") as myfile:
   		responseData += myfile.read().replace('\n', '')
	
	# replace the URL so it will point to static
	responseData = responseData.replace("XXX", Config.localURL() ) 
	

	# now replace the AAA, BBB, etc with the right data
	responseData = responseData.replace("AAA", subprocess.check_output(["date", ""], shell=True))	

	# split uptime at first blank, then at first ,
	uptimeString = subprocess.check_output(["uptime", ""])	
	
	uptimeType = uptimeString.split(",")
	uptimeCount = len(uptimeType)

	if (uptimeCount == 6):
		# over 24 hours
		uptimeSplit = uptimeString.split(",")
		uptimeSplit = uptimeSplit[0]+uptimeSplit[1]
		uptimeSplit = uptimeSplit.split(" ", 1)
		uptimeData = uptimeSplit[1]
	else:	
		# under 24 hours
		uptimeSplit = uptimeString.split(" ", 2)
		uptimeSplit = uptimeSplit[2].split(",", 1)
		uptimeData = uptimeSplit[0]

	responseData = responseData.replace("BBB", uptimeData)	

	usersString = subprocess.check_output(["who", "-q"], shell=False, stderr=subprocess.STDOUT,)	
	responseData = responseData.replace("CCC", usersString)	

	freeString = subprocess.check_output(["free", "-mh"])	
	freeSplit = freeString.split("cache: ", 1)
	freeSplit = freeSplit[1].split("       ", 2)
	freeSplit = freeSplit[2].split("\nSwap:", 1)
	freeData = freeSplit[0]

	responseData = responseData.replace("DDD", freeData)				
	responseData = responseData.replace("EEE", str(fileCount))	
	responseData = responseData.replace("FFF", str(lastFileCount))	

	output = subprocess.check_output(["cat", "/sys/class/thermal/thermal_zone0/temp"])
	cpuTemp = "%3.2f C" % (float(output)/1000.0)
			
	responseData = responseData.replace("GGG", cpuTemp)	
		
	freeString = subprocess.check_output(["ifconfig", "wlan0"])	
	freeSplit = freeString.split("inet addr:", 1)
	freeSplit = freeSplit[1].split(" ", 1)
	freeData = freeSplit[0]

	responseData = responseData.replace("HHH", freeData)	
			
	responseData = responseData.replace("III", Config.localURL())
	# responseData = responseData.replace("III", "'your external address here'")

	responseData = responseData.replace("JJJ", Config.version_number())

	# read latest data from ST-1 SendText control on RasPiConnect 

	try:
		with open ("./local/ST-1.txt", "r") as myfile:
   			sendTextData = myfile.read().replace('\n', '')
   	except IOError:
		sendTextData = "No data"

	responseData = responseData.replace("KKK", sendTextData)
	outgoingXMLData += BuildResponse.buildResponse(responseData)
	outgoingXMLData += BuildResponse.buildFooter()

        if (Config.debug()):
	  print outgoingXMLData	

  return outgoingXMLData
예제 #47
0
def ExecuteUserObjects(objectType, element):


	# Example Objects

	# fetch information from XML for use in user elements

        objectServerID = element.find("./OBJECTSERVERID").text
        objectID = element.find("./OBJECTID").text
	objectAction = element.find(".OBJECTACTION").text	
	objectName = element.find("./OBJECTNAME").text
        objectFlags = element.find("./OBJECTFLAGS").text


        if (Config.debug()):
        	print("objectServerID = %s" % objectServerID)
	# 
	# check to see if this is a Validate request
	#
        validate = Validate.checkForValidate(element)

        if (Config.debug()):
        	print "VALIDATE=%s" % validate

        
	# Build the header for the response

	outgoingXMLData = BuildResponse.buildHeader(element)

	# SS-1 - Server Present 
        if (objectServerID == "SS-1"):

                #check for validate request
                # validate allows RasPiConnect to verify this object is here
                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData

                # normal response requested
		answ = "2"
		#answ = ""
		if (Config.debug()):
			print "In local SS-1"
			print("answ = %s" % answ)
		responseData = answ
		print "sampling weather"
		sendCommandToWeatherPiAndWait("SAMPLEBOTH")

		# now setup internal variables

		setupWeatherStats()
		setupSunAirPlusStats()

                outgoingXMLData += BuildResponse.buildResponse(responseData)
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData
		


	# B-1 - Sample Both and Do All Graphs 
        if (objectServerID == "B-1"):

                #check for validate request
                # validate allows RasPiConnect to verify this object is here
                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData

                # normal response requested
		answ = "OK"
		#answ = ""
		if (Config.debug()):
			print "In local B-1"
			print("answ = %s" % answ)

		print "sampling weather"
		sendCommandToWeatherPiAndWait("SAMPLEBOTHGRAPHS")

		# now setup internal variables

		setupWeatherStats()
		setupSunAirPlusStats()

		responseData = "OK"

                outgoingXMLData += BuildResponse.buildResponse(responseData)
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData
		
	# FB-2 - Graph Selection Feedback
        if (objectServerID == "FB-2"):

                #check for validate request
                # validate allows RasPiConnect to verify this object is here
                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData

                # normal response requested
		responseData = "XXX"
		if (objectName is None):
			objectName = "XXX"
		
		lowername = objectName.lower()
		
		if (lowername == "wind graph"):

			responseData = "temp / hum graph"
			responseData = responseData.title()	
               		f = open("./local/GraphSelect.txt", "w")
               		f.write(lowername)
               		f.close()

		elif (lowername == "temp / hum graph"):

			responseData = "baro graph"
			responseData = responseData.title()	
               		f = open("./local/GraphSelect.txt", "w")
               		f.write(lowername)
               		f.close()

		elif (lowername == "baro graph"):

			responseData = "voltage graph"
			responseData = responseData.title()	
               		f = open("./local/GraphSelect.txt", "w")
               		f.write(lowername)
               		f.close()

		elif (lowername == "voltage graph"):

			responseData = "system logs"
			responseData = responseData.title()	
               		f = open("./local/GraphSelect.txt", "w")
               		f.write(lowername)
               		f.close()
		
		elif (lowername == "system logs"):

			responseData = "current graph"
			responseData = responseData.title()	
               		f = open("./local/GraphSelect.txt", "w")
               		f.write(lowername)
               		f.close()

		elif (lowername == "current graphs"):

			responseData = "wind graph"
			responseData = responseData.title()	
               		f = open("./local/GraphSelect.txt", "w")
               		f.write(lowername)
               		f.close()

		else: 
			# default value
			responseData = "temp / hum graph"
			responseData = responseData.title()	
               		f = open("./local/GraphSelect.txt", "w")
               		f.write(lowername)
               		f.close()




		if (Config.debug()):
			print "In local FB-2"
			print("responseData = %s" % responseData)

                outgoingXMLData += BuildResponse.buildResponse(responseData)
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData
		
	# W-1 - Graph View 
        if (objectServerID == "W-1"):

                #check for validate request
                # validate allows RasPiConnect to verify this object is here
                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData

                # normal response requested
		#answ = ""
		if (Config.debug()):
			print "In local W-1"


		lowername = "voltage graph"

		try:
              		f = open("./local/GraphSelect.txt", "r")
               		tempString = f.read()
               		f.close()
			lowername = tempString 		

		except IOError as e:
			print "I/O error({0}): {1}".format(e.errno, e.strerror)

                
		print "lowername=", lowername	
		if (lowername == "voltage graph"):

			imageName = "PowerVoltageGraph.png"

		elif (lowername == "current graph"):

			imageName = "PowerCurrentGraph.png"
		
		elif (lowername == "baro graph"):

			imageName = "BarometerLightningGraph.png"

		elif (lowername == "temp / hum graph"):

			imageName = "TemperatureHumidityGraph.png"
		
		elif (lowername == "system logs"):

				# grab the system logs
				with open ("./Templates/W-16-SL.html", "r") as myfile:
					import time
					responseData = "System Time: "
					responseData +=  time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
					responseData += "<BR>\n"
    					responseData += myfile.read().replace('\n', '')
		
		        	try:
                			print("trying database")
					DATABASEPASSWORD = "******"
                			db = mdb.connect('localhost', 'root', DATABASEPASSWORD, 'WeatherPi');
		
                			cursor = db.cursor()


					query = "SELECT TimeStamp, Level, Source, Message FROM systemlog ORDER BY ID DESC LIMIT 30"
                			cursor.execute(query)

					rows = cursor.fetchall()
					CRITICAL=50
					ERROR=40
					WARNING=30
					INFO=20
					DEBUG=10
					NOTSET=0

					for row in rows:
						level = row[1]	
						levelName = "NONE"
						if (level == DEBUG):
							levelName = "DEBUG"
						if (level == INFO):
							levelName = "INFO"
						if (level == WARNING):
							levelName = "WARNING"
						if (level == ERROR):
							levelName = "ERROR"
						if (level == CRITICAL):
							levelName = "CRITICAL"

						logline = "%s:%s:%s:%s" % (row[0], levelName, row[2], row[3] )
						line = logline+"<BR>\n<!--INSERTLOGS-->"	

						responseData = responseData.replace("<!--INSERTLOGS-->", line)	



        			except mdb.Error, e:
		
                			print "Error %d: %s" % (e.args[0],e.args[1])

        			finally:
def Execute_Action_Button(root):

	# conditionally import BlinkM
	if (Config.i2c_demo()):
		from pyblinkm import BlinkM, Scripts
	
	
	
	# find the interface object type

	objectServerID = root.find("./OBJECTSERVERID").text
	objectName = root.find("./OBJECTNAME").text
	objectFlags = root.find("./OBJECTFLAGS").text

	validate = Validate.checkForValidate(root)

	if (Config.debug()):
		print("VALIDATE=%s" % validate)

	outgoingXMLData = BuildResponse.buildHeader(root)


	if (Config.debug()):
		print("objectServerID = %s" % objectServerID)


	# we have the objectServerID so now we can choose the correct
	# program

	# FB-1 just does a toggle from on to off from the button name 

	if (objectServerID == "FB-1"):	
		# do a toggle

		#check for validate request
		if (validate == "YES"):
			outgoingXMLData += Validate.buildValidateResponse("YES")
			outgoingXMLData += BuildResponse.buildFooter()

			return outgoingXMLData


		responseData = "XXX"

		lowername = objectName.lower()

		if (lowername.count(" off") > 0):
			
			lowername = lowername.replace(" off", " on")
			responseData = lowername.title()
		
		elif (lowername.count(" on") > 0):
			
			lowername = lowername.replace(" on", " off")
			responseData = lowername.title()
			
		else: 
			responseData = objectName
			
		outgoingXMLData += BuildResponse.buildResponse(responseData)



	# B-1 does a toggle on a BlinkM module on I2C bus address 0xb (11)

	elif (objectServerID == "B-1"):	
		# do a toggle

		#check for validate request
		if (validate == "YES"):
			outgoingXMLData += Validate.buildValidateResponse("YES")
			outgoingXMLData += BuildResponse.buildFooter()

			return outgoingXMLData

		if (Config.debug()):
			print("Config.i2c_demo=%i" % Config.i2c_demo())


		if (Config.i2c_demo()):

			blinkm = BlinkM(1,0xb)
			blinkm.reset()

			try:
				blinkm.go_to(0, 0, 255)
				time.sleep(0.2)
				blinkm.go_to(0, 255, 0)
				responseData = "OK"

			except IOError as e:
				#blinkm.reset()
				print("I/O error({0}): {1}".format(e.errno, e.strerror))
				responseData = "FAILED"
			except:
				blinkm.reset()
				print("Unexpected error:", sys.exc_info()[0])
				raise

		responseData = "OK"

		outgoingXMLData += BuildResponse.buildResponse(responseData)



	else:
		# invalid RaspiConnect Code
		outgoingXMLData += Validate.buildValidateResponse("NO")



	outgoingXMLData += BuildResponse.buildFooter()
	if (Config.debug()):
		print(outgoingXMLData)

	return outgoingXMLData
예제 #49
0
def main():
	today = time.strftime('%Y-%m-%d',time.localtime(time.time()))
	platform_encoding = DetectCode.get_platform_encoding()
	from_station_str = u'出发火车站名: '.encode(platform_encoding)
	to_station_str = u'到达火车站名: '.encode(platform_encoding)
	train_date_str = (u'出发日期(YYYY-MM-DD, e.g., ' + unicode(today) + u'): ').encode(platform_encoding)
	purpose_codes_str = u'是否学生票(Y/N): '.encode(platform_encoding)
	con_message = u'是否继续查询(Y/N) '.encode(platform_encoding)
	error_message = {
		'station_not_exist': u'该火车站不存在,请输入正确的'.encode(platform_encoding),
		'date_format': u'日期格式错误,请重新输入'.encode(platform_encoding)
	}
	input_tip =  u'请输入'.encode(platform_encoding)

	while True:
		message = input_tip
		while True:
			from_station = raw_input(message + from_station_str)
			from_station = from_station.decode(platform_encoding)
			from_station_info = Validate.validate_station(from_station)
			if from_station_info:
				break
			message = error_message['station_not_exist']

		message = input_tip
		while True:
			to_station = raw_input(message + to_station_str)
			to_station = to_station.decode(platform_encoding)
			to_station_info = Validate.validate_station(to_station)
			if to_station_info:
				break
			message = error_message['station_not_exist']

		message = input_tip
		while True:
			train_date = raw_input(message + train_date_str)
			train_date = train_date.decode(platform_encoding)
			if (Validate.validate_date(train_date)):
				break
			message = error_message['date_format']
		
		while True:
			purpose_codes = raw_input(purpose_codes_str)
			purpose_codes = purpose_codes.decode(platform_encoding)
			if purpose_codes in ['Y', 'y', 'N', 'n']:
				break

		if purpose_codes in ['y', 'Y']:
			purpose_codes = '0X00'
		else:
			purpose_codes = 'ADULT'

		params = {
			'train_date': train_date,
			'from_station': from_station_info['station_code'],
			'to_station': to_station_info['station_code'],
			'purpose_codes': purpose_codes		#ADULT
		}
		#print params
		tickets = get_all_tickets(params)
		print_tickets(tickets)
		
		canbuy_tickets = get_all_canbuy_tickets(tickets)
		print_tickets(canbuy_tickets)

		con_message = raw_input(con_message)
		if con_message not in['Y', 'y']:
			break
예제 #50
0
def Execute_Send_Text(root):

	# find the interface object type

	objectServerID = root.find("./OBJECTSERVERID").text
	objectFlags = root.find("./OBJECTFLAGS").text
	objectAction = root.find("./OBJECTACTION").text

	if (objectAction == None):
		objectAction = ""

	if (Config.debug()):
		print("OBJECTACTION=%s" % objectAction)

	validate = Validate.checkForValidate(root)

	if (Config.debug()):
		print("VALIDATE=%s" % validate)

	outgoingXMLData = BuildResponse.buildHeader(root)


	if (Config.debug()):
		print("objectServerID = %s" % objectServerID)


	# we have the objectServerID so now we can choose the correct
	# program

	# ST-1 writes a file called "ST-1.txt" in the ./local directory with the contents of the text field on RasPiConnect

	if (objectServerID == "ST-1"):	

		#check for validate request
		if (validate == "YES"):
			outgoingXMLData += Validate.buildValidateResponse("YES")
			outgoingXMLData += BuildResponse.buildFooter()

			return outgoingXMLData
	
		
		responseData = "OK"

		f = open("./local/ST-1.txt", "w")
		f.write( objectAction)      
		f.close()

		outgoingXMLData += BuildResponse.buildResponse(responseData)



	else:
		# invalid RaspiConnect Code
		outgoingXMLData += Validate.buildValidateResponse("NO")



	outgoingXMLData += BuildResponse.buildFooter()
	if (Config.debug()):
		print(outgoingXMLData)

	return outgoingXMLData
예제 #51
0
def ExecuteUserObjects(objectType, element):

	# Example Objects
	global port25
	global port24

	# fetch information from XML for use in user elements

	#objectServerID is the RasPiConnect ID from the RasPiConnect App

        objectServerID = element.find("./OBJECTSERVERID").text
        objectID = element.find("./OBJECTID").text

        if (Config.debug()):
        	print("objectServerID = %s" % objectServerID)
	# 
	# check to see if this is a Validate request
	#
        validate = Validate.checkForValidate(element)

        if (Config.debug()):
        	print "VALIDATE=%s" % validate

        
	# Build the header for the response

	outgoingXMLData = BuildResponse.buildHeader(element)


	# objects are split up by object types by Interface Constants
	#
	#
	#
	# search for matches to object Type 

	# object Type match
	print("+++++++++++OBJECTTYPE %i" % objectType)
	if (objectType == ACTION_BUTTON_UITYPE):

		if (Config.debug()):
			print "ACTION_BUTTON_UTYPE of %s found" % objectServerID

		# B-2 - play a beep on the Raspberry Pi
		if (objectServerID == "B-2"):	

                	#check for validate request
			# validate allows RasPiConnect to verify this object is here 
                	if (validate == "YES"):
                        	outgoingXMLData += Validate.buildValidateResponse("YES")
                        	outgoingXMLData += BuildResponse.buildFooter()
                        	return outgoingXMLData

			# not validate request, so execute

			# note that python is in the main directory for this call, not the local directory

			output = subprocess.call(["aplay", "sounds/match1.wav"])
			
			responseData = "OK"
                	outgoingXMLData += BuildResponse.buildResponse(responseData)
      			outgoingXMLData += BuildResponse.buildFooter()
                	return outgoingXMLData
	if (objectType == TEXT_DISPLAY_UITYPE):
		
        	if (objectServerID == "LT-1"):	

        	        #check for validate request
                	if (validate == "YES"):
                        	outgoingXMLData += Validate.buildValidateResponse("YES")
                 	        outgoingXMLData += BuildResponse.buildFooter()

                        	return outgoingXMLData

#			output = subprocess.check_output(["cat", "/sys/class/thermal/thermal_zone0/temp"])
			output = GPIO.VERSION
			FMOutput = 1000.0
			
			print "VERSION++++++++++++++=%s" % output

			responseData = "%3.2f, %3.2f, %s" % (FMOutput,FMOutput, output,)

	                outgoingXMLData += BuildResponse.buildResponse(responseData)
     			outgoingXMLData += BuildResponse.buildFooter()
                	return outgoingXMLData
                	
        	if (objectServerID == "LT-2"):	

        	        #check for validate request
                	if (validate == "YES"):
                        	outgoingXMLData += Validate.buildValidateResponse("YES")
                 	        outgoingXMLData += BuildResponse.buildFooter()

                        	return outgoingXMLData

#			output = subprocess.check_output(["cat", "/sys/class/thermal/thermal_zone0/temp"])
			output = GPIO.RPI_REVISION
			FMOutput = 2222.0

			
                        print "VERSION---------=%s" % output



			responseData = "%3.2f, %3.2f, %s" % (output,output, "RPI Version")

	                outgoingXMLData += BuildResponse.buildResponse(responseData)
     			outgoingXMLData += BuildResponse.buildFooter()
                	return outgoingXMLData

	if (objectType == SINGLE_LED_DISPLAY ):

        	        #check for validate request
                	if (validate == "YES"):
                        	outgoingXMLData += Validate.buildValidateResponse("YES")
                 	        outgoingXMLData += BuildResponse.buildFooter()
                        	return outgoingXMLData
			if(port25):
			  GPIO.output(25,0)
			  port25=False
			  ledColour = 5
			  print "Led off"
			else:
			  GPIO.output(25,1)
			  port25=True
			  ledColour=2
			  print "Led on"
			
			responseData = "%i" % (ledColour)


	                outgoingXMLData += BuildResponse.buildResponse(responseData)
     			outgoingXMLData += BuildResponse.buildFooter()
                	return outgoingXMLData	
	if (objectType == FEEDBACK_ACTION_BUTTON_UITYPE):
        	        #check for validate request
                	if (validate == "YES"):
                        	outgoingXMLData += Validate.buildValidateResponse("YES")
                 	        outgoingXMLData += BuildResponse.buildFooter()
                        	return outgoingXMLData
			if(port24):
			  GPIO.output(24,0)
			  port24=False
			  responseData = "Port 24 Led off"
			else:
			  GPIO.output(24,1)
			  port24=True
			  responseData = "port 24 Led on"
			
	                outgoingXMLData += BuildResponse.buildResponse(responseData)
     			outgoingXMLData += BuildResponse.buildFooter()
                	return outgoingXMLData
	else:
		return ""
	# returning a zero length string tells the server that you have not matched 
	# the object and server 
	return ""
예제 #52
0
def ExecuteUserObjects(objectType, element):

    # Example Objects

    # fetch information from XML for use in user elements

    # objectServerID is the RasPiConnect ID from the RasPiConnect App

    objectServerID = element.find("./OBJECTSERVERID").text
    objectID = element.find("./OBJECTID").text
    # find the interface object type
    objectName = element.find("./OBJECTNAME").text
    objectFlags = element.find("./OBJECTFLAGS").text

    if Config.debug():
        print ("objectServerID = %s" % objectServerID)
    #
    # check to see if this is a Validate request
    #
    validate = Validate.checkForValidate(element)

    if Config.debug():
        print "VALIDATE=%s" % validate

    # Build the header for the response

    outgoingXMLData = BuildResponse.buildHeader(element)

    # objects are split up by object types by Interface Constants
    #
    #
    #
    # search for matches to object Type

    # object Type match
    if objectType == COMPLEX_LINE_GRAPH_LIVE_UITYPE:

        if Config.debug():
            print "COMPLEX_LINE_GRAPH_LIVE_UITYPE of %s found" % objectServerID

            # CLGL-1 - ultrasonic graph
        if objectServerID == "CLGL-1":

            # check for validate request
            # validate allows RasPiConnect to verify this object is here
            if validate == "YES":
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

            # normal response requested
            try:
                f = open("/home/pi/MouseAir/state/UltrasonicGraph.txt", "r")
                commandresponse = f.read()
                f.close()
            except IOError as e:
                commandresponse = "0^^0||No Data from MouseAir^^"

            outgoingXMLData += BuildResponse.buildResponse(commandresponse)

            outgoingXMLData += BuildResponse.buildFooter()
            return outgoingXMLData

        # object Type match
    if objectType == SIMPLE_LINE_GRAPH_LIVE_UITYPE:

        if Config.debug():
            print "SIMPLE_LINE_GRAPH_LIVE_UITYPE of %s found" % objectServerID

            # SLGL-1 - ultrasonic graph
        if objectServerID == "SLGL-1":

            # check for validate request
            # validate allows RasPiConnect to verify this object is here
            if validate == "YES":
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

            # normal response requested
            try:
                f = open("/home/pi/MouseAir/state/UltrasonicGraph.txt", "r")
                commandresponse = f.read()
                f.close()
            except IOError as e:
                commandresponse = "0^^0||No Data from MouseAir^^"

            outgoingXMLData += BuildResponse.buildResponse(commandresponse)

            outgoingXMLData += BuildResponse.buildFooter()
            return outgoingXMLData

        # object Type match
    if objectType == PICTURE_REMOTE_WEBVIEW_UITYPE:

        if Config.debug():
            print "PICTURE_REMOTE_WEBVIEW_UITYPE of %s found" % objectServerID

            # W-10 - play a beep on the Raspberry Pi
        if objectServerID == "W-10":

            # check for validate request
            # validate allows RasPiConnect to verify this object is here
            if validate == "YES":
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

            # normal response requested

            imageName = "picamera.jpg"

            responseData = "<html><head>"
            responseData += "<META HTTP-EQUIV='CACHE-CONTROL' CONTENT='NO-CACHE'>"
            responseData += "<title></title><style>body,html,iframe{margin:0;padding:0;}</style>"
            responseData += "</head>"

            responseData += '<body><img src="'
            responseData += Config.localURL()
            responseData += "static/"
            responseData += imageName
            responseData += '" type="jpg" width="585" height="300">'

            responseData += "</body>"

            responseData += "</html>"

            outgoingXMLData += BuildResponse.buildResponse(responseData)

            outgoingXMLData += BuildResponse.buildFooter()
            return outgoingXMLData

        # object Type match
    if objectType == ACTION_BUTTON_UITYPE:

        if Config.debug():
            print "ACTION_BUTTON_UTYPE of %s found" % objectServerID

            # B-10 - fire Mouse
        if objectServerID == "B-10":

            # check for validate request
            # validate allows RasPiConnect to verify this object is here
            if validate == "YES":
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

            # not validate request, so execute

            print "set B-10 Fire Mouse"
            status = sendCommandToMouseAirAndWait("FIREMOUSE")

            responseData = "OK"
            outgoingXMLData += BuildResponse.buildResponse(responseData)
            outgoingXMLData += BuildResponse.buildFooter()
            return outgoingXMLData

        # B-11 - take picture
        if objectServerID == "B-11":

            # check for validate request
            # validate allows RasPiConnect to verify this object is here
            if validate == "YES":
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

            # not validate request, so execute

            print "set B-11 Take Picture"
            status = sendCommandToMouseAirAndWait("TAKEPICTURE")

            responseData = "OK"
            outgoingXMLData += BuildResponse.buildResponse(responseData)
            outgoingXMLData += BuildResponse.buildFooter()
            return outgoingXMLData

        # B-13 - Pan to Mouse watch
        if objectServerID == "B-13":

            # check for validate request
            # validate allows RasPiConnect to verify this object is here
            if validate == "YES":
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

            # not validate request, so execute

            print "set B-13 Pan to Watch Mouse"
            status = sendCommandToMouseAirAndWait("PANTOMOUSE")

            responseData = "OK"
            outgoingXMLData += BuildResponse.buildResponse(responseData)
            outgoingXMLData += BuildResponse.buildFooter()
            return outgoingXMLData

        # B-14 - Pan to Cat watch
        if objectServerID == "B-14":

            # check for validate request
            # validate allows RasPiConnect to verify this object is here
            if validate == "YES":
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

            # not validate request, so execute

            print "set B-14 Pan to Watch Cat"
            status = sendCommandToMouseAirAndWait("PANTOCAT")

            responseData = "OK"
            outgoingXMLData += BuildResponse.buildResponse(responseData)
            outgoingXMLData += BuildResponse.buildFooter()
            return outgoingXMLData

        # B-15 - Shoot Solenoid
        if objectServerID == "B-15":

            # check for validate request
            # validate allows RasPiConnect to verify this object is here
            if validate == "YES":
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

            # not validate request, so execute

            print "set B-15 Shoot Solenoid "
            status = sendCommandToMouseAirAndWait("SHOOTSOLENOID")

            responseData = "OK"
            outgoingXMLData += BuildResponse.buildResponse(responseData)
            outgoingXMLData += BuildResponse.buildFooter()
            return outgoingXMLData

        # B-16 - Pan Left
        if objectServerID == "B-16":

            # check for validate request
            # validate allows RasPiConnect to verify this object is here
            if validate == "YES":
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

            # not validate request, so execute

            print "set B-16 Pan Left"
            status = sendCommandToMouseAirAndWait("PANLEFT")

            responseData = "OK"
            outgoingXMLData += BuildResponse.buildResponse(responseData)
            outgoingXMLData += BuildResponse.buildFooter()
            return outgoingXMLData

        # B-17 - Pan Right
        if objectServerID == "B-17":

            # check for validate request
            # validate allows RasPiConnect to verify this object is here
            if validate == "YES":
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

            # not validate request, so execute

            print "set B-17 Pan Right"
            status = sendCommandToMouseAirAndWait("PANRIGHT")

            responseData = "OK"
            outgoingXMLData += BuildResponse.buildResponse(responseData)
            outgoingXMLData += BuildResponse.buildFooter()
            return outgoingXMLData

        # B-18 - Tilt Up
        if objectServerID == "B-18":

            # check for validate request
            # validate allows RasPiConnect to verify this object is here
            if validate == "YES":
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

            # not validate request, so execute

            print "set B-18 Tilt Up "
            status = sendCommandToMouseAirAndWait("TILTUP")

            responseData = "OK"
            outgoingXMLData += BuildResponse.buildResponse(responseData)
            outgoingXMLData += BuildResponse.buildFooter()
            return outgoingXMLData

        # B-19 - Tilt Down
        if objectServerID == "B-19":

            # check for validate request
            # validate allows RasPiConnect to verify this object is here
            if validate == "YES":
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

            # not validate request, so execute

            print "set B-19 Tilt Down"
            status = sendCommandToMouseAirAndWait("TILTDOWN")

            responseData = "OK"
            outgoingXMLData += BuildResponse.buildResponse(responseData)
            outgoingXMLData += BuildResponse.buildFooter()
            return outgoingXMLData

        # object Type match
    if objectType == FEEDBACK_ACTION_BUTTON_UITYPE:

        if Config.debug():
            print "FEEDBACK_ACTION_BUTTON_UTYPE of %s found" % objectServerID

            # FB-10 -  turn ultrasonics on and off
        if objectServerID == "FB-10":

            # check for validate request
            # validate allows RasPiConnect to verify this object is here
            if validate == "YES":
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

            # not validate request, so execute

            responseData = "XXX"

            if objectName is None:
                objectName = "XXX"

            lowername = objectName.lower()

            if lowername == "ultrasonic on":

                status = sendCommandToMouseAirAndWait("ULTRASONICON")
                responseData = "ultrasonic off"
                responseData = responseData.title()

            elif lowername == "ultrasonic off":

                status = sendCommandToMouseAirAndWait("ULTRASONICOFF")
                responseData = "ultrasonic on"
                responseData = responseData.title()

                # defaults to off
            else:
                status = sendCommandToMouseAirAndWait("ULTRASONICOFF")
                lowername = "ultrasonic on"
                responseData = lowername.title()

            outgoingXMLData += BuildResponse.buildResponse(responseData)
            outgoingXMLData += BuildResponse.buildFooter()
            return outgoingXMLData

        # FB-11 -  turn RFID on and off
        if objectServerID == "FB-11":

            # check for validate request
            # validate allows RasPiConnect to verify this object is here
            if validate == "YES":
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

            # not validate request, so execute

            responseData = "XXX"

            if objectName is None:
                objectName = "XXX"

            lowername = objectName.lower()

            if lowername == "rfid on":

                status = sendCommandToMouseAirAndWait("RFIDON")
                responseData = "RFID off"
                responseData = responseData.title()

            elif lowername == "rfid off":

                status = sendCommandToMouseAirAndWait("RFIDOFF")
                responseData = "RFID on"
                responseData = responseData.title()

                # defaults to off
            else:
                status = sendCommandToMouseAirAndWait("RFIDOFF")
                lowername = "RFID on"
                responseData = lowername.title()

            outgoingXMLData += BuildResponse.buildResponse(responseData)
            outgoingXMLData += BuildResponse.buildFooter()
            return outgoingXMLData

        # FB-12 -  turn USECAMERAMOTION on and off
        if objectServerID == "FB-11":

            # check for validate request
            # validate allows RasPiConnect to verify this object is here
            if validate == "YES":
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

            # not validate request, so execute

            responseData = "XXX"

            if objectName is None:
                objectName = "XXX"

            lowername = objectName.lower()

            if lowername == "camera motion on":

                status = sendCommandToMouseAirAndWait("CAMERAMOTIONON")
                responseData = "camera motion off"
                responseData = responseData.title()

            elif lowername == "camera motion off":

                status = sendCommandToMouseAirAndWait("CAMERAMOTIONOFF")
                responseData = "camera motion on"
                responseData = responseData.title()

                # defaults to off
            else:
                status = sendCommandToMouseAirAndWait("CAMERAMOTIONOFF")
                lowername = "camera motion on"
                responseData = lowername.title()

            outgoingXMLData += BuildResponse.buildResponse(responseData)
            outgoingXMLData += BuildResponse.buildFooter()
            return outgoingXMLData

        # FB-13 -  turn top servo on
        if objectServerID == "FB-13":

            # check for validate request
            # validate allows RasPiConnect to verify this object is here
            if validate == "YES":
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

            # not validate request, so execute

            responseData = "XXX"

            if objectName is None:
                objectName = "XXX"

            lowername = objectName.lower()

            print ("lowername =", lowername)

            if lowername == "top servo close":

                print "set top servo close"
                status = sendCommandToMouseAirAndWait("TOPSERVOCLOSE")
                responseData = "top servo open"
                responseData = responseData.title()

            elif lowername == "top servo open":

                print "set top servo open"
                status = sendCommandToMouseAirAndWait("TOPSERVOOPEN")
                responseData = "top servo close"
                responseData = responseData.title()

                # defaults to top servo closed
            else:
                print "set top servo close"
                status = sendCommandToMouseAirAndWait("TOPSERVOCLOSE")
                lowername = "top servo open"
                responseData = lowername.title()

            outgoingXMLData += BuildResponse.buildResponse(responseData)
            outgoingXMLData += BuildResponse.buildFooter()
            return outgoingXMLData

        # FB-15 -  turn bottom servo on
        if objectServerID == "FB-15":

            # check for validate request
            # validate allows RasPiConnect to verify this object is here
            if validate == "YES":
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

            # not validate request, so execute

            responseData = "XXX"

            if objectName is None:
                objectName = "XXX"

            lowername = objectName.lower()

            print ("lowername =", lowername)

            if lowername == "bottom servo close":

                print "set bottom servo close"
                status = sendCommandToMouseAirAndWait("BOTTOMSERVOCLOSE")
                responseData = "bottom servo open"
                responseData = responseData.title()

            elif lowername == "bottom servo open":

                print "set bottom servo open"
                status = sendCommandToMouseAirAndWait("BOTTOMSERVOOPEN")
                responseData = "bottom servo close"
                responseData = responseData.title()

                # defaults to top servo closed
            else:
                print "set bottom servo close"
                status = sendCommandToMouseAirAndWait("BOTTOMSERVOCLOSE")
                lowername = "bottom servo open"
                responseData = lowername.title()

            outgoingXMLData += BuildResponse.buildResponse(responseData)
            outgoingXMLData += BuildResponse.buildFooter()
            return outgoingXMLData

        # FB-16 -  turn motors on
        if objectServerID == "FB-16":

            # check for validate request
            # validate allows RasPiConnect to verify this object is here
            if validate == "YES":
                outgoingXMLData += Validate.buildValidateResponse("YES")
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData

            # not validate request, so execute

            responseData = "XXX"

            if objectName is None:
                objectName = "XXX"

            lowername = objectName.lower()

            if lowername == "motors on":

                print "set Motors On"
                status = sendCommandToMouseAirAndWait("MOTORSON")
                responseData = "motors Off"
                responseData = responseData.title()

            elif lowername == "motors off":

                status = sendCommandToMouseAirAndWait("MOTORSOFF")
                responseData = "Motors On"
                responseData = responseData.title()

                # defaults to Motors off
            else:
                print "Motors Off"
                status = sendCommandToMouseAirAndWait("MOTORSOFF")
                lowername = "Motors On"
                responseData = lowername.title()

            outgoingXMLData += BuildResponse.buildResponse(responseData)
            outgoingXMLData += BuildResponse.buildFooter()
            return outgoingXMLData

    else:
        return ""
        # returning a zero length string tells the server that you have not matched
        # the object and server
    return ""
예제 #53
0
               	responseData +="</body>"
	
               	responseData += "</html>"


                outgoingXMLData += BuildResponse.buildResponse(responseData)
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData
		
	# AIL-1 - Activity Indicator - LIVE
        if (objectServerID == "AIL-1"):

                #check for validate request
                # validate allows RasPiConnect to verify this object is here
                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData

                # normal response requested
		#answ = "NO"
		answ = "YES"
		#answ = ""
		if (Config.debug()):
			print "In local AIL-1"
			print("answ = %s" % answ)
		responseData = answ

                outgoingXMLData += BuildResponse.buildResponse(responseData)
                outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData
예제 #54
0
파일: Local.py 프로젝트: windy54/RobotPI
def ExecuteUserObjects(objectType, element):

	global led1State
	global led2State
	global forwardState
	global rearState
	global rr

	# Example Objects

	# fetch information from XML for use in user elements

	#objectServerID is the RasPiConnect ID from the RasPiConnect App

        objectServerID = element.find("./OBJECTSERVERID").text
        objectID = element.find("./OBJECTID").text

        if (Config.debug()):
        	print("objectServerID = %s" % objectServerID)
	# 
	# check to see if this is a Validate request
	#
        validate = Validate.checkForValidate(element)

        if (Config.debug()):
        	print "VALIDATE=%s" % validate

        
	# Build the header for the response

	outgoingXMLData = BuildResponse.buildHeader(element)


	# objects are split up by object types by Interface Constants
	#
	#
	#
	# search for matches to object Type 

	# object Type match
	if (objectType == ACTION_BUTTON_UITYPE):
		#print "ACTION_BUTTON_UTYPE of %s found" % objectServerID

		if (Config.debug()):
			print "ACTION_BUTTON_UTYPE of %s found" % objectServerID

		# B-2 - play a beep on the Raspberry Pi
		if (objectServerID == "B-2"):	

                	#check for validate request
			# validate allows RasPiConnect to verify this object is here 
                	if (validate == "YES"):
                        	outgoingXMLData += Validate.buildValidateResponse("YES")
                        	outgoingXMLData += BuildResponse.buildFooter()
                        	return outgoingXMLData

			# not validate request, so execute

			# note that python is in the main directory for this call, not the local directory

			output = subprocess.call(["aplay", "sounds/match1.wav"])
			
			responseData = "OK"
                	outgoingXMLData += BuildResponse.buildResponse(responseData)
      			outgoingXMLData += BuildResponse.buildFooter()
                	return outgoingXMLData
		elif (objectServerID == "B-4"):	
	          #print "button B-4"

                  #check for validate request
                  if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()

                        return outgoingXMLData

                  if(led1State):
                    led1State=False
		    responseData = "OFF"
		    rr.set_led1(False)
		    rr.stop()
		    #print "led1 true"
		  else:
                    led1State=True
		    responseData = " ON"
		    rr.set_led1(True)
		    rr.right()
		    #print "led1 false"
		  responseData = "OK"
                  outgoingXMLData += BuildResponse.buildResponse(responseData)
      		  outgoingXMLData += BuildResponse.buildFooter()
                  return outgoingXMLData
		elif (objectServerID == "B-5"):	
	          #print "button B-5"

                  #check for validate request
                  if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()

                        return outgoingXMLData

                  if(led2State):
                    led2State=False
		    responseData = "OFF"
		    rr.set_led2(False)
		    rr.stop()
		    #print "led2 true"
		  else:
                    led2State=True
		    responseData = " ON"
		    rr.set_led2(True)
		    rr.left()
		    #print "led2 false"
		  responseData = "OK"
                  outgoingXMLData += BuildResponse.buildResponse(responseData)
      		  outgoingXMLData += BuildResponse.buildFooter()
                  return outgoingXMLData		
		elif (objectServerID == "B-6"):	
		  #forwards
	          #print "button B-4"

                  #check for validate request
                  if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()

                        return outgoingXMLData

                  if(forwardState):
                    forwardState=False
		    responseData = "OFF"
		    rr.set_led1(False)
		    rr.set_led2(False)
		    rr.stop()
		    #print "forward true"
		  else:
                    forwardState=True
		    responseData = " ON"
		    rr.set_led1(False)
		    rr.set_led2(False)
		    rr.forward()
		    #print "forward false"
		  responseData = "OK"
                  outgoingXMLData += BuildResponse.buildResponse(responseData)
      		  outgoingXMLData += BuildResponse.buildFooter()
                  return outgoingXMLData
		elif (objectServerID == "B-7"):	
		  # rear
	          #print "button B-7"

                  #check for validate request
                  if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()

                        return outgoingXMLData

                  if(rearState):
                    rearState=False
		    responseData = "OFF"
		    rr.set_led1(False)
		    rr.set_led2(False)
		    rr.stop()
		    #print "led2 true"
		  else:
                    rearState=True
		    responseData = " ON"
		    rr.set_led1(True)
		    rr.set_led2(True)
		    rr.reverse()
		    #print "led2 false"
		  responseData = "OK"
                  outgoingXMLData += BuildResponse.buildResponse(responseData)
      		  outgoingXMLData += BuildResponse.buildFooter()
                  return outgoingXMLData	
		elif (objectServerID == "B-8"):	
		  # rear
	          #print "button B-8"

                  #check for validate request
                  if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()

                        return outgoingXMLData
		  rr.stop()
		  os.system("sudo shutdown -h now")
		  responseData = "OK"
                  outgoingXMLData += BuildResponse.buildResponse(responseData)
      		  outgoingXMLData += BuildResponse.buildFooter()
                  return outgoingXMLData	

	elif (objectServerID == "W-2"):
			if (validate == "YES"):
				outgoingXMLData += Validate.buildValidateResponse("YES")
				outgoingXMLData += BuildResponse.buildFooter()
				return outgoingXMLData
			
			os.system("raspistill -o static/camImage.jpg -t 0")	
			imageName = "camImage.jpg"	

			responseData = "<html><head>"
			responseData += "<title></title><style>body,html,iframe{margin:0;padding:0;}</style>"
			responseData += "</head>"	
			responseData += "<body><img src=\""
 			responseData += Config.localURL()
 			responseData += "static/"
			responseData += imageName
			responseData += "\" type=\"jpg\" width=\"300\" height=\"300\">"
			responseData += "<BR>Picture<BR>"
			responseData +="</body>static"		
			responseData += "</html>"		
			outgoingXMLData += BuildResponse.buildResponse(responseData)
      		  	outgoingXMLData += BuildResponse.buildFooter()
	                return outgoingXMLData			

        		if (Config.debug()):
				print outgoingXMLData	
	elif (objectServerID == "FB-1"):	
		# do a toggle
		print "FB-1"

                #check for validate request
                if (validate == "YES"):
                        outgoingXMLData += Validate.buildValidateResponse("YES")
                        outgoingXMLData += BuildResponse.buildFooter()
                        return outgoingXMLData	


		responseData = "False"
		if (rr.sw1_closed()):
		  responseData = "True "

	
                outgoingXMLData += BuildResponse.buildResponse(responseData)
 	  	outgoingXMLData += BuildResponse.buildFooter()
                return outgoingXMLData	
	else:
		return ""
	# returning a zero length string tells the server that you have not matched 
	# the object and server 
	return ""
예제 #55
0
파일: Converge.py 프로젝트: xtina/ExamiNDR
def main():
    if len(sys.argv) < 3:
        print "Usage: %s <fasta_file> [width = None ] [options]"%(re.sub('^.*/','',sys.argv[0]))
        print "Options include:"
        print "                  -valid  <tf_name> Check answers against Transfac"
        print " EM Parameters:"
        print "                  -beta    [0.01]   Beta for pseudocounts"
        print "                  -seedbeta[0.02]   Beta for pseudocounts for seeds from text"
        print "                  -gamma   [0.2]    Gamma (fraction of sequences)"
        print "                  -delta   [0.001]  Convergence criteria"
        print " "
        print " Seeds (not actually proper priors)"
        print "                  -prior            Seqences or motifs for seeds (may be repeated)"
        print "                  -top N   [0]      Include w-mers in top N probes"
        print "                  -gap    string    sample gapped motifs"
        print "                  -TF               Seed with (all) TRANSFAC PSSMs (buggy)"
        print "                  -info <file.info> for structural priors"
        print "                  -pad              add NN..NN to seed"
        print " "
        print " Genome / Background model "
        print "                  -human (250,1000) Use Human Background model"
        print "                  -Y2K, -Y5C        Use Yeast Upstream Intergenic regions (2000, 500)"
        print "                  -B                Use Bacterial Orfs"
        print " " 
        print "Examples:"
        print " %s t.fsa 5 -prior GGGTA -prior AAAAAC "%(sys.argv[0].split('/')[-1])
        print "   will start an EM with 3 seeds: GGGTA, AAAAA, and AAAAC"
        print 
        print " %s t.fsa 5 -info CUP9.info -gamma 0.5 "%(sys.argv[0].split('/')[-1])
        print "   will start an EM with Enriched seeds in CUP9.info, with"
        print "   Gamma expectation of 50% of all probes"
        print 
        print " %s t.fsa -prior MCM1_5.tamo:0 "%(sys.argv[0].split('/')[-1])
        print "   will start an EM with 0th motif of the file MCM1_5.tamo"
        print "   as a seed"
        print 
        sys.exit(1)
    fastafile = sys.argv[1] 

    #Echo the command line
    print "#" + ' '.join(map(lambda x: re.sub(' ','\ ',x), sys.argv))

    if sys.argv[2].isdigit():
        width = sys.argv[2]
    else: width = None
    
    algorithm = ''
    beta      = ''
    seedbeta  = ''
    cbeta     = ''
    deltamin  = ''
    gamma     = 0.2
    infofile  = ''
    seedmodels= []
    species   = 'YEAST'
    valid_tfs = []
    gapped_syl= None
    gapflank  = 0
    gapweight = 0.2
    enrichfact= 0.7
    pmax      = 0  #False
    TFSEEDS   = 0
    TFMids    = []
    pad       = None
    padlen    = 0
    thetas    = []
    seed_count = 0   #Default: Take the top 0
    seed_s     = []  #Initialize seq array
    sp_seed   = 0
    
    '''Parse command-line arguments'''
    for tok,i in zip(sys.argv,xrange(len(sys.argv))):
        if   tok == '-top'   :   seed_count = int(sys.argv[i+1])
        elif tok == '-greedy':   algorithm  = "GREEDY"
        elif tok == '-prior' :   seed_s.append(sys.argv[i+1])
        elif tok == 'sp'     :   sp_seed    = 1
        elif tok == '-beta'  :   beta       = float(sys.argv[i+1])
        elif tok == '-beta'  :   seedbeta   = float(sys.argv[i+1])
        elif tok == '-cbeta' :   cbeta      = float(sys.argv[i+1])
	elif tok == '-thetas':   
		for j in range(int(sys.argv[i+1])):
			thetas.append(float(sys.argv[i+j+2]))
        elif tok == '-gamma' :   gamma      = float(sys.argv[i+1])
        elif tok == '-delta' :   deltamin   = float(sys.argv[i+1])
        elif tok == '-info'  :   infofile   = sys.argv[i+1]
        elif tok == '-valid' :   valid_tfs.append(sys.argv[i+1])
        elif tok == '-w'     :   width      = sys.argv[i+1]
        elif tok == '-width' :   width      = sys.argv[i+1]
        elif tok == '-gap'   :   gapped_syl = sys.argv[i+1]
        elif tok == '-gapflank' :gapflank   = int(sys.argv[i+1])
        elif tok == '-gapweight':gapweight  = float(sys.argv[i+1])
        elif tok == '-enrichfact':enrichfact= float(sys.argv[i+1])
        elif tok == '-pmax'  :   pmax       = 1
        elif tok == '-Y2K'   :   species    = "YEAST_2000_UP"
        elif tok == '-Y5C'   :   species    = "YEAST_500_UP"
        elif tok == '-B'     :   species    = "BAC_ORF"
        elif tok == '-Ch22'  :   species    = "Ch22"
        elif tok == '-genome':   species    = sys.argv[i+1]
        elif tok == '-pad'   :
            pad        = sys.argv[i+1]
            padlen     = sys.argv[i+2]     
        elif tok == '-TF'    :
            TFSEEDS = 1
            for j in range(i+1,len(sys.argv)):
                if re.match('M0',sys.argv[j]):
                    TFMids.append(sys.argv[j])
                else:
                    break
        elif tok == '-human' :
            _s = ''
            if sys.argv[i+1].isdigit(): _s = '_'+sys.argv[i+1]
            else:                       _s = ''
            species    = 'HUMAN'+_s

    seqs = []
    fsaD     = Fasta.load(fastafile)
    probes = fsaD.keys()
    '''
    for probeid in fsaD.keys():
        seqs.append  (fsaD    [probeid])
    '''
    numprobes = len(probes)
    #print "numprobes: %i"%numprobes
    if not ('-random_background' in sys.argv or '-nomarkov' in sys.argv):
        EM.loadMarkovBackground(fastafile,numprobes,species)

    #seqs     = EM.fasta2seqs(fastafile)
    all_seqs = seqs
    seed_s.extend(seqs[0:min(seed_count,len(seqs))])
    #not necessary --- seed_c.extend(c_seqs[0:min(seed_count,len(seqs))])

    if infofile and width=='info':
        width = info2width(infofile)
    elif width != None:
        width = int(width)

    #Alternate source of seeds
    if infofile:
        if 1 or width:
            seedmodels.extend(info2seeds(width,infofile,fastafile,species))
        else:
            print 'Error: need to specify motif width w/ .info file'
    
    #Any -prior pointers to motifs in other files?
    (seed_s, motifs) = parse_priors(seed_s)
    seedmodels.extend(motifs)

    #Should we get seeds from TRANSFAC?
    if TFSEEDS:
        tf = []
        D  = tfmats()
        if not TFMids:
            keys = D.keys()
        else:
            keys = []
            for TFMid in TFMids:
                for key in D.keys():
                    if key[0:6] == TFMid:
                        keys.append(key)
                        break
        for key in keys:
            m = D[key]
            m.seednum = int(re.sub('M0*','',key.split()[0]))
            m.seedtxt = '%-24s %s'%(m,key)
            tf.append(m)
        tf.sort(lambda x,y: cmp(x.seednum,y.seednum))
        seedmodels.extend(tf)
        #seedmodels.append(tf[33])

    if gapped_syl:
        gapped_priors = gapped_motifs(gapped_syl)
        gapped_priors = map(lambda x:'N'+x+'N', gapped_priors)
        seed_s.extend(gapped_priors)

    if pad:
        print '# Padding models with NN-m-NN'
        newmodels = []
        for m in seedmodels:
            newmodels.append(m[-2,m.width+2])
        seedmodels = newmodels

    '''
    Set everything up and GO!!
    '''
    global theEM
    theEM = EM.EM(seed_s,[],[],width,"VERBOSE")
    if beta:     theEM.beta     = beta
    if cbeta:    theEM.cbeta    = cbeta
    if deltamin: theEM.deltamin = deltamin
    if seedbeta: theEM.seedbeta = seedbeta
    if thetas:   theEM.thetas = thetas
    theEM.param['gamma']        = gamma
    theEM.probeids.extend(probes)
    theEM.seqs.extend(all_seqs)
    #theEM.cons_seqs.extend(c_seqs)
    theEM.models    = seedmodels
    theEM.gapflank  = gapflank
    theEM.gapweight = gapweight
    theEM.report()
    theEM.EM_Cstart()    #GO!!

    #print "#Sorting candidates"
    #sys.stdout.flush()
    #EM.candidates.sort(lambda x,y: cmp(y.MAP,x.MAP))

    #sys.exit(0)
    
    '''
    Compute some metrics
    '''
    print "#Loading Genome %s"%species ; sys.stdout.flush()
    if species == 'human':
	Genome = ProbeSet('HUMAN',enrichfact)
    else:
    	Genome = ProbeSet(species,enrichfact)
    ids    = Genome.ids_from_file(fastafile)

    #fsaDict = Fasta.load(fastafile)
    #probes = fsaDict.keys()
    #cons_pickle = fastafile.split('.')[0] + '.cpickle'
    for C in theEM.candidates:
        #p_cons = conservation_pvalue(C.pssm,probes,fsaDict,ConsDict,4)
        #print p_cons
        if not pmax:
            w_dict = Genome.w_dict
            for key,i in zip(w_dict.keys(),range(len(C.pssm.thetas))):
                w_dict[key] = C.pssm.thetas[i]
            Genome.w_dict = w_dict
            C.pssm.pvalue = Genome.p_value(C.pssm,ids,'verbose')
            #print "P-VAL: %f"%(Genome.p_value(C.pssm,ids,'verbose')*p_cons)
            C.pssm.church = Genome.church(C.pssm,ids)
        else:
            (p,frac) = Genome.best_p_value(C.pssm,ids)
            C.pssm.pvalue    = p
            C.pssm.threshold = frac * C.pssm.maxscore
            print "Bests:",p,frac

    for valid_tf in valid_tfs:
        C.pssm.valid = Validate.validate(C.pssm,valid_tf,'Verbose',"Want Tuple")
    
    '''
    Print out all motifs (sorted by Enrichment) in an AlignACE-like form
    '''

    theEM.candidates.sort(lambda x,y: cmp(x.pssm.pvalue,y.pssm.pvalue))
    for C,i in zip(theEM.candidates,range(len(theEM.candidates))):
        C.pssm.maxscore = -100  #May have side effects.  Recompute when done
        if C.pssm.valid:
            _t = C.pssm.valid
            if not _t[0]:
                vstring = "(--- %8.4f %8.4f %s)"%(_t[1],_t[2],_t[3])
            else:
                vstring = "(HIT %8.4f %8.4f %s)"%(_t[1],_t[2],_t[3])
        else:
            vstring = ''
        C.pssm._maxscore()     #Recomputed
        print "Log-odds matrix for Motif %3d %s"%(i,C)
        C.pssm._print_ll()
        print "Sequence Logo"
        C.pssm._print_bits()
        flush()
        #print '# %3d matching sequences at 90%%'%len(C.pssm.bestseqs(C.pssm.maxscore * 0.9))
        flush()
        m = C.pssm
        if not m.__dict__.has_key('gamma'):  m.gamma = None #Kludge to deal w/ old shelves
        if m.seedtxt:     print "Seed: %3d %s"%(i,m.seedtxt)
        if m.source:      print "Source: ",m.source
        if m.gamma:       print "Gamma: %7.5f"%m.gamma
        if m.threshold:   print "Threshold: %5.2f"%m.threshold
        if m.thetas != []:
            tstr = "thetas:"
            for theta in m.thetas:
                tstr = tstr + " " + str(theta)
            print tstr                                    
        #if C.pssm.seedtxt:
        #    print 'Seed  %3d %-25s'%(i,C.pssm.seedtxt)
        if C.pssm.church != None: vstring = 'ch: %5.2f  %s'%(
            math.fabs(math.log(C.pssm.church)/math.log(10)), vstring)
        print "Motif %3d %-25s  nlog(p): %6.3f  %s"%(i,C,-math.log(C.pssm.pvalue)/math.log(10),vstring)
        if C.pssm.threshold:
            print "Threshold: %6.3f  %4.1f%%"%(
                C.pssm.threshold, 100.0*C.pssm.threshold/C.pssm.maxscore)
            

        C.pssm.maxscore = -1e100  #May have side effects.  Recompute when done
        for seq in C.wmers:
            print seq,i,C.pssm.scan(seq)[2][0]
        C.pssm._maxscore()      #Recomputed
        print '*'*len(seq)
        print "MAP Score: %f"%C.MAP
        sys.stdout.flush()
    sys.stdout.flush()
    sys.exit(0) #Avoid ridiculous python cleanup times
def ExecuteUserObjects(objectType, element):

	# Example Objects

	# fetch information from XML for use in user elements

	#objectServerID is the RasPiConnect ID from the RasPiConnect App

        objectServerID = element.find("./OBJECTSERVERID").text
        objectID = element.find("./OBJECTID").text

        if (Config.debug()):
        	print("objectServerID = %s" % objectServerID)
	# 
	# check to see if this is a Validate request
	#
        validate = Validate.checkForValidate(element)

        if (Config.debug()):
        	print "VALIDATE=%s" % validate

        
	# Build the header for the response

	outgoingXMLData = BuildResponse.buildHeader(element)

	#
	# B-1 Flashes LED on GPIO
	if (objectServerID == "B-1"):	

               	#check for validate request
		# validate allows RasPiConnect to verify this object is here 

               	if (validate == "YES"):
                       	outgoingXMLData += Validate.buildValidateResponse("YES")
                       	outgoingXMLData += BuildResponse.buildFooter()
                       	return outgoingXMLData

		# not validate request, so execute
		#
		
		#
		#
		# Execute your code
		#
		#

		# To put an LED on GPIO Pin 7 on your pi read this:
		#		http://www.thirdeyevis.com/pi-page-2.php
		#
        	if (Config.debug()):
        		print("Button # %s: Blinking GPIO pin 7" % objectServerID)

		GPIO.output(7,True) ## Turn on GPIO pin 7
		time.sleep(1) ## sleep 1 second
		GPIO.output(7,False) ## Turn off GPIO pin 7
              	responseData = "OK" ## send an OK back to the App

		print "responseData =", responseData

		#
		#
		# Done with your code
		#
		#

               	outgoingXMLData += BuildResponse.buildResponse(responseData)
      		outgoingXMLData += BuildResponse.buildFooter()
               	return outgoingXMLData
		


	else:
		# returning a zero length string tells the server that you have not matched 
		# the object and server 
		return ""
예제 #57
0
def ExecuteUserObjects(objectType, element):

    # Example Objects

    # fetch information from XML for use in user elements

    #objectServerID is the RasPiConnect ID from the RasPiConnect App

    objectServerID = element.find("./OBJECTSERVERID").text
    objectID = element.find("./OBJECTID").text

    if (Config.debug()):
        print("objectServerID = %s" % objectServerID)
#
# check to see if this is a Validate request
#
    validate = Validate.checkForValidate(element)

    if (Config.debug()):
        print "VALIDATE=%s" % validate

# Build the header for the response

    outgoingXMLData = BuildResponse.buildHeader(element)

    #
    # B-1 Flashes LED on GPIO
    if (objectServerID == "B-1"):

        #check for validate request
        # validate allows RasPiConnect to verify this object is here

        if (validate == "YES"):
            outgoingXMLData += Validate.buildValidateResponse("YES")
            outgoingXMLData += BuildResponse.buildFooter()
            return outgoingXMLData

# not validate request, so execute
#

#
#
# Execute your code
#
#

# To put an LED on GPIO Pin 7 on your pi read this:
#		http://www.thirdeyevis.com/pi-page-2.php
#
        if (Config.debug()):
            print("Button # %s: Blinking GPIO pin 7" % objectServerID)

        GPIO.output(7, True)  ## Turn on GPIO pin 7
        time.sleep(1)  ## sleep 1 second
        GPIO.output(7, False)  ## Turn off GPIO pin 7
        responseData = "OK"  ## send an OK back to the App

        print "responseData =", responseData

        #
        #
        # Done with your code
        #
        #

        outgoingXMLData += BuildResponse.buildResponse(responseData)
        outgoingXMLData += BuildResponse.buildFooter()
        return outgoingXMLData

    else:
        # returning a zero length string tells the server that you have not matched
        # the object and server
        return ""
def Generate_Remote_WebView(root, LOCALURL):

       	if (Config.i2c_demo()):
		from pyblinkm import BlinkM, Scripts

	
	objectServerID = root.find("./OBJECTSERVERID").text
        objectFlags = root.find("./OBJECTFLAGS").text
	
	validate = Validate.checkForValidate(root) 

        if (Config.debug()):
		print "VALIDATE=%s" % validate

	outgoingXMLData = BuildResponse.buildHeader(root)

	if (objectServerID == "W-1"):
	
		#check for validate request
		if (validate == "YES"):
			outgoingXMLData += Validate.buildValidateResponse("YES")
			outgoingXMLData += BuildResponse.buildFooter()

			return outgoingXMLData
			
		# normal response requested	
	
		responseData = ""

		# check to see if i2c_demo is turned on
		if (Config.i2c_demo()):
		
        		if (Config.debug()):
				print "Config.i2c_demo passed as True" 


			# Yes, it is on

			# Initialise the BMP085 and use STANDARD mode (default value)
			# bmp = BMP085(0x77, debug=True)
			# bmp = BMP085(0x77)
		
			# To specify a different operating mode, uncomment one of the following:
			# bmp = BMP085(0x77, 0)  # ULTRALOWPOWER Mode
			# bmp = BMP085(0x77, 1)  # STANDARD Mode
			# bmp = BMP085(0x77, 2)  # HIRES Mode
			bmp = BMP085(0x77, 3)  # ULTRAHIRES Mode
			
			count = 0
			exceptionCount = 0
			exceptionCountBMP = 0
			blinkm = BlinkM(1,0xc)
			blinkm.reset()
			
	
			
			try:
				temp = bmp.readTemperature()
				pressure = bmp.readPressure()
				altitude = bmp.readAltitude()
		
				tempData = "%.2f C" % temp
				pressureData = "%.2f hPa" % (pressure / 100.0)

			except IOError as e:
    				exceptionCountBMP = exceptionCountBMP + 1	
				print "I/O error({0}): {1}".format(e.errno, e.strerror)
			except:
    				exceptionCountBMP = exceptionCountBMP + 1	
    				print "Unexpected error:", sys.exc_info()[0]
    				raise

		else:    # now set some values for display since we don't have i2C
			tempData = "xx.x C (no i2c enabled)" 
			pressureData = "xxxx.x hPa (no i2c enabled)" 

				

		# read an HTML template into aw string		
		with open ("./Templates/W-1.html", "r") as myfile:
    			responseData += myfile.read().replace('\n', '')
	
		# replace the URL so it will point to static
		responseData = responseData.replace("XXX", LOCALURL) 
	

		# now replace the AAA, BBB, etc with the right data
		responseData = responseData.replace("AAA", subprocess.check_output(["date", ""], shell=True))	

		# split uptime at first blank, then at first ,
		uptimeString = subprocess.check_output(["uptime", ""])	
	
		uptimeType = uptimeString.split(",")
		uptimeCount = len(uptimeType)

		if (uptimeCount == 6):
			# over 24 hours
			uptimeSplit = uptimeString.split(",")
			uptimeSplit = uptimeSplit[0]+uptimeSplit[1]
			uptimeSplit = uptimeSplit.split(" ", 1)
			uptimeData = uptimeSplit[1]
		else:	
			# under 24 hours
			uptimeSplit = uptimeString.split(" ", 2)
			uptimeSplit = uptimeSplit[2].split(",", 1)
			uptimeData = uptimeSplit[0]

		responseData = responseData.replace("BBB", uptimeData)	

		usersString = subprocess.check_output(["who", "-q"], shell=False, stderr=subprocess.STDOUT,)	
		responseData = responseData.replace("CCC", usersString)	

		freeString = subprocess.check_output(["free", "-mh"])	
		freeSplit = freeString.split("cache: ", 1)
		freeSplit = freeSplit[1].split("       ", 2)
		freeSplit = freeSplit[2].split("\nSwap:", 1)
		freeData = freeSplit[0]


		responseData = responseData.replace("DDD", freeData)	
			
		responseData = responseData.replace("EEE", tempData)	
		responseData = responseData.replace("FFF", pressureData)	


		output = subprocess.check_output(["cat", "/sys/class/thermal/thermal_zone0/temp"])
		cpuTemp = "%3.2f C" % (float(output)/1000.0)
			
		responseData = responseData.replace("GGG", cpuTemp)	
		
		freeString = subprocess.check_output(["ifconfig", "eth0"])	
		freeSplit = freeString.split("inet addr:", 1)
		freeSplit = freeSplit[1].split(" ", 1)
		freeData = freeSplit[0]

		responseData = responseData.replace("HHH", freeData)	
			
		responseData = responseData.replace("III", Config.localURL())
		# responseData = responseData.replace("III", "'your external address here'")

		responseData = responseData.replace("JJJ", Config.version_number())

		# read latest data from ST-1 SendText control on RasPiConnect 

		try:
			with open ("./local/ST-1.txt", "r") as myfile:
    				sendTextData = myfile.read().replace('\n', '')
   		except IOError:
			sendTextData = ""

		responseData = responseData.replace("KKK", sendTextData)

	

		# check to see if i2c_demo is turned on
		if (Config.i2c_demo()):
		
			time.sleep(0.2)

   	 		try:
	
               			blinkm.go_to(255, 0, 0)
				time.sleep(0.2)
               			blinkm.go_to(0, 255, 0)
	
	
       			except IOError as e:
             			#blinkm.reset()
                		exceptionCount = exceptionCount + 1
                		print "I/O error({0}): {1}".format(e.errno, e.strerror)
        		except:
               			blinkm.reset()
                		exceptionCount = exceptionCount + 1
                		print "Unexpected error:", sys.exc_info()[0]
                		raise
	
		#responseData += subprocess.check_output(["cat", "/proc/cpuinfo"])
		#responseData += subprocess.check_output(["cat", "/proc/meminfo"])
		
		outgoingXMLData += BuildResponse.buildResponse(responseData)

        	if (Config.debug()):
			print outgoingXMLData	
	elif (objectServerID == "W-2"):
	
		#check for validate request
		if (validate == "YES"):
			outgoingXMLData += Validate.buildValidateResponse("YES")
			outgoingXMLData += BuildResponse.buildFooter()

			return outgoingXMLData
			
		# normal response requested	

		imageName = "RovioImage.jpg"	


		responseData = "<html><head>"
		responseData += "<title></title><style>body,html,iframe{margin:0;padding:0;}</style>"
		responseData += "</head>"
		
		responseData += "<body><img src=\""
 		responseData += LOCALURL 
 		responseData += "static/"
		responseData += imageName
		responseData += "\" type=\"jpg\" width=\"300\" height=\"300\">"
		responseData += "<BR>Picture<BR>"

		responseData +="</body>"
		
		responseData += "</html>"
	
		
		outgoingXMLData += BuildResponse.buildResponse(responseData)

        	if (Config.debug()):
			print outgoingXMLData	

	else:
		# invalid RaspiConnect Code
		outgoingXMLData += Validate.buildValidateResponse("NO")	
	

	outgoingXMLData += BuildResponse.buildFooter()

	return outgoingXMLData