def GenAirplanes(self):
        iNbAirplanes = random.randint(10, 15)
        i = 0
        Output.debug("Generating %d airplanes" % iNbAirplanes)
        lstCityNames = sorted(WorldMap.keys())
        while i < iNbAirplanes:
            szOrigin = random.choice(lstCityNames)
            j = random.randint(0, len(lstCityNames) - 1)
            k = 0
            while k < len(lstCityNames):
                szDestination = lstCityNames[(j + k) % len(lstCityNames)]
                iDistance = (WorldMap[szDestination][0] - WorldMap[szOrigin][0]
                             )**2 + (WorldMap[szDestination][1] -
                                     WorldMap[szOrigin][1])**2
                if iDistance >= 100000 and (abs(WorldMap[szDestination][0] -
                                                WorldMap[szOrigin][0]) > 100):
                    break
                k += 1

            if k < len(lstCityNames):
                szId = "A_%.4d" % random.randint(10 * i, 10 * i + 9)
                self.__dicAirplanes[szId] = CAirplane(szId, szOrigin,
                                                      szDestination)
                i += 1

        return True
예제 #2
0
	def HandleData(self, Pesticide, szData, Answer):
		szAnswer = ""
		dicData = {}

		dicData = utils.ParseAnswer(szData)
		if dicData == None:
			return False

		# Analyze command 
		if dicData["CODE"] == "LIST":
			Output.debug("Command LIST received")
			if self.__HandleList(Pesticide, dicData, Answer) == False:
				return False
		elif dicData["CODE"] == "INFO":
			Output.debug("Command INFO received")
			if self.__HandleInfo(VERSION, PROTOCOL, DESC, STATUS, dicData, Answer) == False:
				return False
		elif dicData["CODE"] == "INC":
			Output.debug("Command INC received")
			if self.__HandleInc(Pesticide, dicData, Answer) == False:
				return False
		elif dicData["CODE"] == "DEC":
			Output.debug("Command DEC received")
			if self.__HandleDec(Pesticide, dicData, Answer) == False:
				return False
		else:
			Output.debug("Unknown command \"%s\"" % dicData["CODE"])
			return False

		return True
예제 #3
0
def ReadTextFile(szFilePath):
	try:
		f = open(szFilePath, "r")
		try:
			return f.read()
		finally:
			f.close()
			Output.debug('File "%s" successfully loaded' % szFilePath)
	except:
		Output.exception('Exception while trying to read file "%s"' % szFilePath)
		return None
예제 #4
0
def ReadTextFile(szFilePath):
	try:
		f = open(szFilePath, "r")
		try:
			return f.read()
		finally:
			f.close()
			Output.debug('File "%s" successfully loaded' % szFilePath)
	except:
		Output.exception('Exception while trying to read file "%s"' % szFilePath)
		return None
예제 #5
0
	def __HandleDec(self, Pesticide, dicData, Answer):
		if dicData.has_key("INGREDIENT") == False:
			Output.debug("Missing ingredient")
			return False
		if dicData.has_key("VALUE") == False:
			Output.debug("Missing value")
			return False
		iValue = int(dicData["VALUE"])
		if Pesticide.DecIngredient(dicData["INGREDIENT"], iValue) == False:
			return False
		Answer.S("OK")
		return True
    def HandleData(self, AirplaneDatabase, szData, Answer):
        szAnswer = ""
        dicData = {}

        dicData = utils.ParseAnswer(szData)
        if dicData == None:
            return False

        # If the request contains an ID, all communication must be signed
        if dicData.has_key("ID") == True:
            Airplane = AirplaneDatabase.GetAirplane(dicData["ID"])
            if Airplane == None:
                return False

            # Get the shared key
            szKey = Airplane.GetKey()

            # Activate signature in the answer
            Answer.Z(szKey)

            # Check signature in the request
            if dicData.has_key("SIGN") == False:
                Output.debug("Missing signature")
                return False

            szSign = dicData["SIGN"]

            del dicData["SIGN"]
            if utils.ComputeSign(dicData, szKey) != szSign:
                Output.debug("Invalid signature")
                return False

        # Analyze command
        if dicData["CODE"] == "LIST":
            Output.debug("Command LIST received")
            if self.__HandleList(AirplaneDatabase, dicData, Answer) == False:
                return False
        elif dicData["CODE"] == "SETPOS":
            Output.debug("Command SETPOS received")
            if self.__HandleSetPos(AirplaneDatabase, dicData, Answer) == False:
                return False
        else:
            Output.debug("Unknown command \"%s\"" % dicData["CODE"])
            return False

        return True
예제 #7
0
	def SetPosition(self, X, Y):
		iDiff = int(math.sqrt((X-self.Px) ** 2 + (Y-self.Py) ** 2))
		if iDiff > 100:
			Output.debug("Trying to update position of a too big value: %d" % iDiff)
			return False

		Output.debug("Update position of value: %d" % iDiff)
		self.Px = X
		self.Py = Y
		Output.debug("Position of airplane %s is now [%d,%d]" % (self.__szId, self.Px, self.Py))
		angle = math.atan(float(abs(self.Dy-self.Py))/float(abs(self.Dx-self.Px)))
		Output.debug("Angle is %f (was %f)" % (angle, self.angle))
		return True
예제 #8
0
def ParseAnswer(szData):
	# Extract the command
	lstData = szData.split('\n')
	if len(lstData[0]) == 0:
		return None

	# Parse the data
	dicData = {}
	for szLine in lstData:
		if len(szLine) == 0:
			continue
		m = re.search("([^=]+)=(.+)", szLine)
		if m == None:
			Output.debug("Invalid line \"%s\"" % szLine)
			print szData
			return None
		else:
			dicData[m.group(1)] = m.group(2)

	return dicData
예제 #9
0
    def SetPosition(self, X, Y):
        iDiff = int(math.sqrt((X - self.Px)**2 + (Y - self.Py)**2))
        if iDiff > 100:
            Output.debug("Trying to update position of a too big value: %d" %
                         iDiff)
            return False

        Output.debug("Update position of value: %d" % iDiff)
        self.Px = X
        self.Py = Y
        Output.debug("Position of airplane %s is now [%d,%d]" %
                     (self.__szId, self.Px, self.Py))
        angle = math.atan(
            float(abs(self.Dy - self.Py)) / float(abs(self.Dx - self.Px)))
        Output.debug("Angle is %f (was %f)" % (angle, self.angle))
        return True
예제 #10
0
	def DecIngredient(self, szIngredient, iValue):
		if self.d.has_key(szIngredient) == False:
			Output.debug("Ingredient %s not present" % szIngredient)
			return False
		if self.d[szIngredient] <= iValue:
			Output.debug("Impossible to decrement %s of %d mg" % (szIngredient, iValue))
			return False

		self.d[szIngredient] -= iValue
		Output.debug("Ingredient %s is now at %d mg" % (szIngredient, self.d[szIngredient]))
		return True
예제 #11
0
	def IncIngredient(self, szIngredient, iValue):
		if self.d.has_key(szIngredient) == False:
			Output.debug("Ingredient %s not present" % szIngredient)
			return False
		if self.d[szIngredient] + iValue >= 1000:
			Output.debug("Impossible to increment %s of %d mg; Amount would be higher than critical threshold" % (szIngredient, iValue))
			return False

		self.d[szIngredient] += iValue
		Output.debug("Ingredient %s is now at %d mg" % (szIngredient, self.d[szIngredient]))
		return True
예제 #12
0
    def DecIngredient(self, szIngredient, iValue):
        if self.d.has_key(szIngredient) == False:
            Output.debug("Ingredient %s not present" % szIngredient)
            return False
        if self.d[szIngredient] <= iValue:
            Output.debug("Impossible to decrement %s of %d mg" %
                         (szIngredient, iValue))
            return False

        self.d[szIngredient] -= iValue
        Output.debug("Ingredient %s is now at %d mg" %
                     (szIngredient, self.d[szIngredient]))
        return True
예제 #13
0
    def IncIngredient(self, szIngredient, iValue):
        if self.d.has_key(szIngredient) == False:
            Output.debug("Ingredient %s not present" % szIngredient)
            return False
        if self.d[szIngredient] + iValue >= 1000:
            Output.debug(
                "Impossible to increment %s of %d mg; Amount would be higher than critical threshold"
                % (szIngredient, iValue))
            return False

        self.d[szIngredient] += iValue
        Output.debug("Ingredient %s is now at %d mg" %
                     (szIngredient, self.d[szIngredient]))
        return True
예제 #14
0
    def __HandleSetPos(self, AirplaneDatabase, dicData, Answer):
        if dicData.has_key("ID") == False:
            Output.debug("Missing id")
            return False
        if dicData.has_key("POSX") == False:
            Output.debug("Missing posx")
            return False
        if dicData.has_key("POSY") == False:
            Output.debug("Missing posy")
            return False

        Airplane = AirplaneDatabase.GetAirplane(dicData["ID"])
        if Airplane == None:
            return False

        if Airplane.SetPosition(int(dicData["POSX"]),
                                int(dicData["POSY"])) == False:
            return False

        Answer.S("OK")
        return True
예제 #15
0
	elif o == '-i':
		INTERACTIVE=True
	elif o == '-v':
		if OUTPUT_LEVEL == logging.INFO:
			OUTPUT_LEVEL = logging.DEBUG
		elif OUTPUT_LEVEL > 0:
			OUTPUT_LEVEL -= 10
	elif o == "-h":
		Usage()
	else:
		Output.error('Invalid option "%s"' % o)
		Usage(-1)

Output.setLevel(OUTPUT_LEVEL)

Output.debug("Starting server on %s:%s" % (LISTEN, PORT))
Server = ThreadedTCPServer((LISTEN, PORT), ThreadedTCPRequestHandler)
ServerThread = threading.Thread(target=Server.serve_forever)
ServerThread.daemon = True
ServerThread.start()
Output.debug("Server successfully started")
if INTERACTIVE == True:
	while True:
		sys.stdout.write("> ")
		szCmd = sys.stdin.readline().rstrip('\n')
		if len(szCmd) == 0:
			continue
		elif szCmd == "quit":
			break
		else:
			Output.error("Invalid command \"%s\"" % szCmd)