def _initialize_socket(self): if config.debugLevelEnabled(config.INFO): print 'Socket: Establishing connection to server {0} at port {1}'.format(self.url, self.port) try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((self.url, self.port)) greeting = self._receive() if greeting != Socket.GREETING: if config.debugLevelEnabled(config.ERROR): print ('Socket: Invalid greeting received from server {0} at port {1}: {2}' .format(self.url, self.port, greeting)) sys.exit(1) else: message = 'agent 1' self.sendExpectNoResponse(message) except socket.error as e: if config.debugLevelEnabled(config.ERROR): print ('Socket: Error occurred while attempting to establish connection with server {0} at port {1}: {2}' .format(self.url, self.port, e)) sys.exit(1) if config.debugLevelEnabled(config.INFO): print 'Socket: Connection successfully established'
def _initialize_socket(self): if config.debugLevelEnabled(config.INFO): print 'Socket: Establishing connection to server {0} at port {1}'.format( self.url, self.port) try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((self.url, self.port)) greeting = self._receive() if greeting != Socket.GREETING: if config.debugLevelEnabled(config.ERROR): print( 'Socket: Invalid greeting received from server {0} at port {1}: {2}' .format(self.url, self.port, greeting)) sys.exit(1) else: message = 'agent 1' self.sendExpectNoResponse(message) except socket.error as e: if config.debugLevelEnabled(config.ERROR): print( 'Socket: Error occurred while attempting to establish connection with server {0} at port {1}: {2}' .format(self.url, self.port, e)) sys.exit(1) if config.debugLevelEnabled(config.INFO): print 'Socket: Connection successfully established'
def listObstacles(self): if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Sending listObstacles request' response = self.socket.sendExpectListResponse('obstacles') if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Response for listObstacles request = {0}'.format(response) return Obstacle.parseList(response.getList())
def listEnemyTanks(self): if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Sending listEnemyTanks request' response = self.socket.sendExpectListResponse('othertanks') if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Response for listEnemyTanks request = {0}'.format(response) return EnemyTank.parseList(response.getList())
def listTeams(self): if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Sending listTeams request' response = self.socket.sendExpectListResponse('teams') if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Response for listTeams request = {0}'.format( response) return Team.parseList(response.getList())
def shoot(self, tank): if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Ordering tank {0} to shoot'.format(tank) response = self.socket.sendExpectStandardResponse('shoot {0}'.format(tank)) if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Response for shoot order = {0}'.format(response) elif not response.isOk() and config.debugLevelEnabled(config.WARN): print 'ServerProxy: Attempted to shoot tank {0}, but it hasn\'t reloaded yet'.format(tank) return response
def getSurroundings(self, tank): if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Sending getSurroundings request' response = self.socket.sendExpectListResponse('occgrid {0}'.format(tank)) if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Response for listConstants request = {0}'.format(response) occList = response.getList() if len(occList) > 0: return OccGrid.parseList(response.getList()) else: return None
def setTurnRate(self, tank, rate): if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Ordering tank {0} to set turn rate to {1}'.format(tank, rate) if rate > 1: print 'ServerProxy: Limiting tank turn rate to 1' rate = 1 elif rate < -1: print 'ServerProxy: Limiting tank turn rate to -1' rate = -1 response = self.socket.sendExpectStandardResponse('angvel {0} {1}'.format(tank, rate)) if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Response for setTurnRate order = {0}'.format(response)
def shoot(self, tank): if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Ordering tank {0} to shoot'.format(tank) response = self.socket.sendExpectStandardResponse( 'shoot {0}'.format(tank)) if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Response for shoot order = {0}'.format( response) elif not response.isOk() and config.debugLevelEnabled(config.WARN): print 'ServerProxy: Attempted to shoot tank {0}, but it hasn\'t reloaded yet'.format( tank) return response
def getSurroundings(self, tank): if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Sending getSurroundings request' response = self.socket.sendExpectListResponse( 'occgrid {0}'.format(tank)) if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Response for listConstants request = {0}'.format( response) occList = response.getList() if len(occList) > 0: return OccGrid.parseList(response.getList()) else: return None
def setVelocity(self, tank, speed): if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Ordering tank {0} to set velocity to {1}'.format(tank, speed) if speed > 1: print 'ServerProxy: Limiting tank speed to 1' speed = 1 elif speed < -1: print 'ServerProxy: Limiting tank speed to -1' speed = -1 response = self.socket.sendExpectStandardResponse('speed {0} {1}'.format(tank, speed)) if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Response for setVelocity order = {0}'.format(response) return response
def setTurnRate(self, tank, rate): if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Ordering tank {0} to set turn rate to {1}'.format( tank, rate) if rate > 1: print 'ServerProxy: Limiting tank turn rate to 1' rate = 1 elif rate < -1: print 'ServerProxy: Limiting tank turn rate to -1' rate = -1 response = self.socket.sendExpectStandardResponse( 'angvel {0} {1}'.format(tank, rate)) if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Response for setTurnRate order = {0}'.format( response)
def setVelocity(self, tank, speed): if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Ordering tank {0} to set velocity to {1}'.format( tank, speed) if speed > 1: print 'ServerProxy: Limiting tank speed to 1' speed = 1 elif speed < -1: print 'ServerProxy: Limiting tank speed to -1' speed = -1 response = self.socket.sendExpectStandardResponse( 'speed {0} {1}'.format(tank, speed)) if config.debugLevelEnabled(config.TRACE): print 'ServerProxy: Response for setVelocity order = {0}'.format( response) return response
def aim(self, target, status): if config.debugLevelEnabled(config.DEBUG): print "ArtemisAgent: my angle = {}".format(degrees(status.angle)) newAngle = self._calculateAngle((status.x, status.y), target) turnRate = self._calcTurn(newAngle, degrees(status.angle)) if self._shouldShoot(target, (status.x, status.y), status.angle): return tuple(["shoot"]) else: return tuple(["turn", turnRate])
def _run(self): while True: now = time.time() if config.debugLevelEnabled(config.DEBUG): print 'KalmanFilter: filtering' next_wakeup = now + self.delta_t self._doPredictions() sleepLength = next_wakeup - time.time() time.sleep(sleepLength)
def _takeAction(self, prediction): if prediction != "": if config.debugLevelEnabled(config.DEBUG): print "ArtemisAgency: Enemy predicted at {}".format(prediction) tanks = self.server.listFriendlyTanks() for i in xrange(len(self.agents)): action = self.agents[i].aim(prediction, tanks[i]) if action[0] == "turn": self.server.setTurnRate(i, action[1]) elif action[0] == "shoot": self.server.shoot(i)
def _calcVector(self, vectorList): deltaX = 0 deltaY = 0 for vector in vectorList: deltaX += vector[0] deltaY += vector[1] if config.debugLevelEnabled(config.TRACE): print "DeltaX = {0}, DeltaY = {1}".format(deltaX, deltaY) angle, magnitude = self._deltaToVelocity(deltaX, deltaY) return angle, magnitude
def __init__(self, enemy, obsQueue, predQueue, interval): self.iteration_count = 15 self.enemy = enemy self.obsQueue = obsQueue self.predQueue = predQueue if config.debugLevelEnabled(config.INFO): print "KalmanFilter: Initializing" self._setConstants(interval) self._run()
def _calcTurn(self, newAngle, myAngle): angle = newAngle - myAngle if angle > 180: angle -= 360 elif angle < -180: angle += 360 if abs(angle) > 5: rate = copysign(1, angle) else: rate = 0 if config.debugLevelEnabled(config.DEBUG): print "ArtemisAgent: Desired angle = {0:.2f}, Angle = {1:.2f}, Rate = {2:.2f}".format( newAngle, myAngle, rate) return rate
def _takeAction(self): for i in range(len(self.agents)): action = self.agents[i].getAction() if action != "": if config.debugLevelEnabled(config.TRACE): print "Action" + action + str(i) if action == "move": self.server.setVelocity(i, 1) elif action == "stopMove": self.server.setVelocity(i, 0) elif action == "turn": self.server.setTurnRate(i, 1) elif action == "stopTurn": self.server.setTurnRate(i, 0) elif action == "shoot": self.server.shoot(i)
def getAction(self, fieldList, status): now = time.time() if config.debugLevelEnabled(config.TRACE): print "my angle" print degrees(status.angle) if len(self.moveTimes) == 0: vectorList = self._createVectors(fieldList, status.x, status.y) newAngle, newVelocity = self._calcVector(vectorList) if newAngle != 0: self._calcTurn(newAngle, degrees(status.angle)) return tuple(["speed", newVelocity]) elif self.moveTimes[0] < now: action = self.moveList[self.moveTimes[0]] del self.moveList[self.moveTimes[0]] del self.moveTimes[0] return action else: return tuple([""])
def _receive(self): fullResponse = '' while 1: data = self.socket.recv(self.RECV_SIZE) # if config.debugLevelEnabled(config.TRACE): # print 'Socket: Receive loop, received "{0}"'.format(data) if not data.startswith(Socket.ACKNOWLEDGE): fullResponse += data lastLine = data.strip().split('\n')[-1] if any([lastLine.startswith(eom) for eom in Socket.END_OF_MESSAGE_LIST]): break fullResponse = fullResponse.strip() if config.debugLevelEnabled(config.TRACE): print 'Socket: Received "{0}"'.format(fullResponse) return fullResponse
def sendExpectStandardResponse(self, message): response = self._handleSend(message, True) lines = response.split('\n') responseLine = 0 if lines[responseLine].startswith(Socket.ACKNOWLEDGE): # setVelocity or setTurnRate 1 comes back as 1.0 if lines[responseLine].endswith(message): responseLine += 1 else: if config.debugLevelEnabled(config.WARN): print ('Socket: WARN: Received acknowledge line that doesn\'t match message. ' + 'Message = "{0}", Response = "{1}"').format(message, response) return FailResponse([]) splitResponse = response[responseLine].split(' ', 1) if splitResponse[0] == Socket.OK_RESPONSE: return OkResponse(splitResponse[1:]) else: return FailResponse(splitResponse[1:])
def _calcTurn(self, newAngle, myAngle): angle = newAngle - myAngle if angle > 180: angle -= 360 elif angle < -180: angle += 360 now = time.time() duration = .2 stop = now + duration if abs(angle) < 5: speed = 0 elif abs(angle) > 90: speed = copysign(1, angle) else: #speed = (angle/18) * .1 + .2 speed = copysign(.5, angle) if config.debugLevelEnabled(config.TRACE): print "Desired angle = {0:.2f}, Angle = {1:.2f}, Speed = {2:.2f}".format( newAngle, angle, speed) self.moveTimes.append(now) self.moveList[now] = tuple(["turn", speed])
def _receive(self): fullResponse = '' while 1: data = self.socket.recv(self.RECV_SIZE) # if config.debugLevelEnabled(config.TRACE): # print 'Socket: Receive loop, received "{0}"'.format(data) if not data.startswith(Socket.ACKNOWLEDGE): fullResponse += data lastLine = data.strip().split('\n')[-1] if any([ lastLine.startswith(eom) for eom in Socket.END_OF_MESSAGE_LIST ]): break fullResponse = fullResponse.strip() if config.debugLevelEnabled(config.TRACE): print 'Socket: Received "{0}"'.format(fullResponse) return fullResponse
def sendExpectStandardResponse(self, message): response = self._handleSend(message, True) lines = response.split('\n') responseLine = 0 if lines[responseLine].startswith(Socket.ACKNOWLEDGE): # setVelocity or setTurnRate 1 comes back as 1.0 if lines[responseLine].endswith(message): responseLine += 1 else: if config.debugLevelEnabled(config.WARN): print( 'Socket: WARN: Received acknowledge line that doesn\'t match message. ' + 'Message = "{0}", Response = "{1}"').format( message, response) return FailResponse([]) splitResponse = response[responseLine].split(' ', 1) if splitResponse[0] == Socket.OK_RESPONSE: return OkResponse(splitResponse[1:]) else: return FailResponse(splitResponse[1:])
def _send(self, message): if config.debugLevelEnabled(config.TRACE): print 'Socket: Sending "{0}"'.format(message) self.socket.send(message + '\n')
def _init(self): if config.debugLevelEnabled(config.INFO): print "ArtemisAgency: Initializing" for tank in self.server.listFriendlyTanks(): self.agents.append(ArtemisAgent())
def _addToObservations(self): if config.debugLevelEnabled(config.DEBUG): print 'ArtemisAgency: observing' observations = self.server.listEnemyTanks() self.obsQueue.put(observations)
def _close_socket(self): if config.debugLevelEnabled(config.INFO): print 'Socket: Closing connection' self.socket.close()
parser.add_argument('-d', '--debuglevel') return parser def startKalman(obsQueue, predQueue, args, interval): time.sleep(interval / 2.0) KalmanClient(obsQueue, predQueue, args, interval) if __name__ == "__main__": parser = _get_parser() args = parser.parse_args() if args.debuglevel: print "Setting debug level to {}".format(args.debuglevel) config.setDebugLevelFromString(args.debuglevel) obsQueue = Queue() predQueue = Queue() interval = .75 if config.debugLevelEnabled(config.INFO): print 'Constantina: Starting child processes' p = Process(target=startKalman, args=(obsQueue, predQueue, args, interval)) p.start() ArtemisClient(obsQueue, predQueue, args, interval)