예제 #1
0
 def checkRequestedResources(
     self
 ):  #check to see if we need to resend a query request for one of the resources we requested
     result = id.Id(value=id.Id().zeroId)
     for key in Main.requestedResources:
         requestedResource = Main.requestedResources[key]
         if requestedResource[3] < requestedResource[
                 1] and requestedResource[5] + 10 < time.time():
             result = id.Id(value=key)
             break
     return result
예제 #2
0
	def __init__(self, fileName, description):
		idObject = id.Id()
		self.id = idObject
		self.fileName = fileName
		self.description = description
		self.fileBytes = open(("resources/" + fileName),"rb").read()
		self.mimeType = mimetypes.guess_type(fileName)[0]
예제 #3
0
def main():

    logging.basicConfig(level=logging.DEBUG)

    eva_id = id.Id()
    eva_ego = ego.Ego()
    eva_perception = perception.Perception()
    eva_memory = memory.Memory()
    eva_interface = interface.Interface()

    eva_mind = mind.Mind('Eva', eva_id, eva_ego)

    timer_control = time.time()

    while eva_mind.is_active:

        if timer_control + TIME_CYCLE > time.time():
            continue

        eva_id.Process(eva_mind)
        eva_ego.Process(eva_mind)
        eva_perception.Process(eva_mind)
        eva_mind.Process(eva_memory, eva_perception)

        for response in eva_mind.responses:
            eva_interface.PrintResponse(response)

        eva_mind.responses.clear()

        timer_control = time.time()

    return eva_mind.return_state
예제 #4
0
 def mainLoop(self):
     ids = id.Id()  #Create an id object
     while self.running:
         if Main.state == "join":
             if self.thread.name != "monty":
                 while Main.state == "join":
                     pass  #trap the threads that aren't monty
             else:
                 #TODO: send our IP# to joiner, clear out peers array, set peers array with response from joiner
                 Main.changeState(self, "participate")
         elif Main.state == "joining":
             if self.thread.name != "monty":
                 while Main.state == "joining":
                     pass  #trap the thread that aren't monty
             else:
                 #TODO: listen for IP#s for x amount of time, assign people their new peers and send them, set peers
                 Main.changeState(self, "participate")
         elif Main.state == "not in":
             if not Main.commandQueue.empty():
                 Main.handleCommandQueue(self, Main.commandQueue.get())
             else:
                 ids.idFactory()
         elif Main.state == "participate":
             if not Main.multicastQueue.empty():
                 Main.changeState(self, "join")
             elif not Main.commandQueue.empty():
                 Main.handleCommandQueue(self, Main.commandQueue.get())
             elif not Main.sendQueue.empty():
                 Main.handleSendQueue(self, Main.sendQueue.get())
             elif not Main.receiveQueue.empty():
                 Main.handleReceiveQueue(self, Main.receiveQueue.get())
             else:
                 requestedResource = Main.checkRequestedResources(self)
                 if requestedResource.getAsHex() != id.Id(
                         value=id.Id().zeroId).getAsHex():
                     Main.requestPartNumber(
                         self,
                         partNumber=Main.requestedResources[
                             requestedResource.getAsHex()][4],
                         resourceId=requestedResource,
                         requestId=Main.requestedResources[
                             requestedResource.getAsHex()][7])
                 else:
                     ids.idFactory()
예제 #5
0
 def requestPartNumber(self, partNumber, resourceId, requestId):
     requestedResource = Main.requestedResources[resourceId.getAsHex()]
     resourcePartTtl = timeToLive.TimeToLive()
     resourcePart = id.Id().getAsBytes() + bytearray(
         struct.pack(">I", partNumber))
     resourcePartMessage = UDPMessage.UDPMessage(requestId,
                                                 resourceId,
                                                 ttl=resourcePartTtl,
                                                 message=resourcePart)
     requestedResource[5] = time.time()
     Main.addToSendQueue(
         self, [resourcePartMessage.getDataGramPacket(), "127.0.0.1"])
예제 #6
0
 def handleCommandQueue(
     self, object
 ):  #object is a command from the user with the command type as the 0th element and the parameter of the search as the 1st element
     command = object[0]
     argument = object[1]
     if command == "query":
         id1 = id.Id()
         if len(argument) != (id.Id().idLengthInBytes * 2):
             for key in Main.foundResources:
                 foundResource = Main.foundResources[key]
                 if argument == foundResource[3]:
                     id2 = id.Id(value=key)
                     Main.requestMap[id1.getAsHex()] = [
                         "query", key
                     ]  #adds the value to the requestMap dictionary, making note of the fact that it was a send
                     Main.requestedResources[key] = [
                         foundResource[0], foundResource[1],
                         foundResource[2], "", 1,
                         time.time(), foundResource[3], id1
                     ]
                     Main.requestPartNumber(self,
                                            partNumber=1,
                                            resourceId=id2,
                                            requestId=id1)
         else:
             id2 = id.Id(value=argument)
             if id2.getAsHex() in Main.foundResources:
                 foundResource = Main.foundResources[id2.getAsHex()]
                 Main.requestMap[id1.getAsHex()] = [
                     "query", id2.getAsHex()
                 ]  #adds the value to the requestMap dictionary, making note of the fact that it was a send
                 Main.requestedResources[id2.getAsHex()] = [
                     foundResource[0], foundResource[1], foundResource[2],
                     "", 1,
                     time.time(), foundResource[3], id1
                 ]
                 Main.requestPartNumber(self,
                                        partNumber=1,
                                        resourceId=id2,
                                        requestId=id1)
             else:
                 Main.addToAlertQueue(self, "Unknown resource: " + argument)
     elif command == "find":
         id1 = id.Id()
         id2 = id.Id()
         ttl = timeToLive.TimeToLive()
         message = UDPMessage.UDPMessage(id1=id1,
                                         id2=id2,
                                         ttl=ttl,
                                         message=argument)
         Main.requestMap[id1.getAsHex()] = [
             "find", argument
         ]  #adds the value to the requestMap dictionary, making note of the fact that it was a find
         Main.addToSendQueue(
             self, [message.getDataGramPacket(), "127.0.0.1"
                    ])  #127.0.0.1 is used to show it came from the user
예제 #7
0
	def __init__(self, id1=None, id2=None, ttl=None, message=None, byteArray=None, lastPacket = False):
		idObject = id.Id()
		ttlObject = timeToLive.TimeToLive()
		
		if byteArray == None:
			if id1.isIncorrectLength():
				print "ERROR: Id1 is the wrong length"
			else:
				self.id1 = id1
				
			if id2.isIncorrectLength():
				print "ERROR: Id2 is the wrong length"
			else:
				self.id2 = id2

			if ttl.isIncorrectLength():
				print "ERROR: TTL is the wrong length"
			else:
				self.ttl = ttl
			
			if len(message) > 476:
				print "ERROR: Message is too long"
				#Send Error
			elif len(message) < 476 and lastPacket == False:
				while len(message) < 476:
					#Pad Message
					message = message + "|"
					
			self.message = message
			
		else:
			self.byteArray = byteArray
			self.id1 = id.Id(value = bytearray(byteArray[:idObject.idLengthInBytes]))
			self.id2 = id.Id(value = bytearray(byteArray[idObject.idLengthInBytes: idObject.idLengthInBytes*2]))
			self.ttl = timeToLive.TimeToLive(timeToLive = bytearray(byteArray[idObject.idLengthInBytes*2:(idObject.idLengthInBytes*2 + ttlObject.sizeInBytes)]))
			self.message = byteArray[(idObject.idLengthInBytes*2 + ttlObject.sizeInBytes):]
예제 #8
0
 def handleReceiveQueue(
     self, object
 ):  #object is an array with the datagramPacket as the 0th element and the IP address that we got it from orginally as the 1st element
     message = UDPMessage.UDPMessage(byteArray=object)
     if message.ttl.ttl > 0:
         message.ttl.dec()
         Main.addToSendQueue(
             self, [message.getDataGramPacket(), object[1]
                    ])  #no matter what we pass the message onto our peers
         if message.id2.getAsHex(
         ) in Main.requestMap:  #check if the message is a response to one of our messages
             if Main.requestMap[message.id2.getAsHex(
             )][0] == "query":  #check if our message was a query
                 messagePartNumber = struct.unpack(
                     ">I", message.
                     message[message.id1.
                             idLengthInBytes:message.id1.idLengthInBytes +
                             4])[0]  #4 is the size of the partNumber
                 if messagePartNumber == Main.requestedResources[
                         message.id1.getAsHex(
                         )][4]:  #check to see if the message has the part number that matches that last one that we requested
                     Main.requestedResources[message.id1.getAsHex(
                     )][3] = Main.requestedResources[
                         message.id1.getAsHex()][3] + "" + message.message[
                             message.id1.idLengthInBytes +
                             4:]  #4 is the size of the partNumber
                     Main.requestedResources[message.id1.getAsHex(
                     )][4] = Main.requestedResources[
                         message.id1.getAsHex()][4] + 1
                     if len(
                             message.message
                     ) < 456:  #check to see if this was the last part
                         Main.addToAlertQueue(
                             self, "Resource " + message.id1.getAsHex() +
                             " has been received.")
                         Main.completedResources[message.id1.getAsHex()] = [
                             Main.requestedResources[message.id1.getAsHex()]
                             [0], Main.requestedResources[
                                 message.id1.getAsHex()][3],
                             Main.requestedResources[message.id1.getAsHex()]
                             [2], Main.requestedResources[
                                 message.id1.getAsHex()][6]
                         ]
                     else:
                         Main.requestPartNumber(
                             self,
                             partNumber=Main.requestedResources[
                                 message.id1.getAsHex()][4],
                             resourceId=message.id1,
                             requestId=Main.requestedResources[
                                 message.id1.getAsHex()][7])
             else:  #otherwise it was a find
                 if message.id1.getAsHex(
                 ) not in Main.foundResources:  #we don't need to put it in the foundResources dictionary if it's already there
                     findMessageResponse = message.message[id.Id().
                                                           idLengthInBytes:]
                     delimiter = findMessageResponse[:1]
                     responseArray = findMessageResponse.split(delimiter)
                     Main.addToAlertQueue(
                         self, "Found resource " + message.id1.getAsHex() +
                         ". The description of the resource is '" +
                         responseArray[3] + "' The length in bytes is " +
                         responseArray[2] + ". The MimeType is " +
                         responseArray[1] + ". Its local id is: " +
                         str(Main.localIdCounter))
                     Main.foundResources[message.id1.getAsHex()] = [
                         responseArray[3], responseArray[2],
                         responseArray[1],
                         str(Main.localIdCounter)
                     ]
                     Main.localIdCounter = Main.localIdCounter + 1
         else:  #the message was not related to us
             if message.id2.getAsHex(
             ) in Main.resourcesMap:  #treat as a query
                 partNumberBytes = message.message[
                     id.Id().idLengthInBytes:id.Id().idLengthInBytes +
                     4]  #the part number of the requested resource
                 partNumber = struct.unpack(">I", partNumberBytes)[0]
                 requestedResource = Main.resourcesMap[
                     message.id2.getAsHex()]
                 resourcePartTtl = timeToLive.TimeToLive()
                 if 456 * (int(partNumber)) < int(
                         requestedResource.getSizeInBytes()):
                     resourcePart = id.Id().getAsBytes(
                     ) + partNumberBytes + requestedResource.fileBytes[
                         456 * (int(partNumber) - 1):456 *
                         (int(partNumber))]
                     resourcePartMessage = UDPMessage.UDPMessage(
                         id1=requestedResource.id,
                         id2=message.id1,
                         ttl=resourcePartTtl,
                         message=resourcePart)
                 else:
                     resourcePart = id.Id().getAsBytes(
                     ) + partNumberBytes + requestedResource.fileBytes[
                         456 * (int(partNumber) - 1):]
                     resourcePartMessage = UDPMessage.UDPMessage(
                         id1=requestedResource.id,
                         id2=message.id1,
                         ttl=resourcePartTtl,
                         message=resourcePart,
                         lastPacket=True)
                 Main.addToSendQueue(
                     self,
                     [resourcePartMessage.getDataGramPacket(), "127.0.0.1"])
             else:  #treat as a find
                 for key in Main.resourcesMap:  #loop through all of our resources
                     resource = Main.resourcesMap[key]
                     if Main.removePadding(
                             self, message.message
                     ) in resource.description:  #check if we have a matching resource
                         responseId1 = resource.id
                         responseId2 = message.id1
                         responseTtl = timeToLive.TimeToLive()
                         responseMessage = id.Id().getAsBytes(
                         ) + "|" + resource.mimeType + "|" + resource.getSizeInBytes(
                         ) + "|" + resource.description
                         responseDatagram = UDPMessage.UDPMessage(
                             id1=responseId1,
                             id2=responseId2,
                             ttl=responseTtl,
                             message=responseMessage)
                         Main.addToSendQueue(self, [
                             responseDatagram.getDataGramPacket(),
                             "127.0.0.1"
                         ])
예제 #9
0
def echo_handler(conn, cli_addr):
    while True:
        try:
            data = conn.recv(1024).decode('utf-8')
            if not data:
                try:
                    for name, value in connections.items():
                        if value == conn:
                            data = name
                    if data in connections:
                        if ":" not in data:
                            x = serial.Serial(data)
                            subprocess.call('sudo rm -r /var/www/html/' + x +
                                            '.jpg',
                                            shell=True)
                        del connections[data]
                    print('Client closing: {}'.format(cli_addr))
                    break  # 연결 끊길때 서버에 사진지우고 끊는 부분
                except:
                    print('Client closing: {}'.format(cli_addr))
                    break  # 카메라 연결 끊긴 부분
            print('Received: {}'.format(data))
            if "-" in data:
                chid = data.split("-")
                chid = chid[0] + "\n"
                data = id.Id(chid)
                data = data + "\n"
                connections[data].sendall(
                    chid.encode('utf-8'))  # 카메라번호 받아서 아이디 디비
            elif "/" in data:
                sign = signup.Signup(data) + "\n"
                conn.sendall(sign.encode('utf-8'))  # 회원가입 디비 들어갈 곳
            elif "?" in data:
                if data.split("?")[0] + "\n" in connections:
                    conn.sendall("already\n".encode('utf-8'))
                elif data.split("?")[0] + ":\n" in connections:
                    conn.sendall("already\n".encode('utf-8'))
                else:
                    log = login.Login(data)  # 로그인 디비 들어갈 곳
                    log = log + "\n"
                    conn.sendall(log.encode('utf-8'))
            elif "logout" in data:
                for name, value in connections.items():
                    if value == conn:
                        data = name
                if data in connections:
                    del connections[data]
                data = data.replace(":\n", "\n")
                if data in connections:
                    del connections[data]  # logout시 딕셔너리에서 카메라 소켓 제거
            else:
                if "_" not in data:
                    data = serial.Serial(data)
                    data1 = data + "\n"
                    data2 = data + "-\n"
                    if data1 in connections:
                        connections[data1].sendall(
                            data2.encode('utf-8'))  # 아이디 받아서 카메라번호 디비
                        conn.sendall("start\n".encode('utf-8'))
                    else:
                        conn.sendall("finish\n".encode('utf-8'))
                elif "_" in data:
                    data = data.replace('_\n', '\n')
                    data = serial.Serial(data)
                    subprocess.call('sudo rm -r /var/www/html/' + data +
                                    '.jpg',
                                    shell=True)
                    data1 = data + "\n"
                    data2 = data + "_\n"
                    connections[data1].sendall(
                        data2.encode('utf-8'))  # 종료 눌렀을시 대기상태

        except socket.error as e:
            print('socket error: {}'.format(e))
            break
    conn.close()