Ejemplo n.º 1
0
class Communicator():

    def __init__(self, messageHandler):

        # the tcp listener, that handles incoming connections on tcp.
        self.TCPReceiver = TCPReceiver("129.241.187.145", 0, messageHandler)
        self.TCPReceiver.start()

        # the udp listener that gets broadcasting messages.
        self.UDPReceiver = UDPReceiver(6005, messageHandler)
        self.UDPReceiver.start()

        # the tcp and udp senders.
        self.TCPSender = TCPSender("129.241.187.145", 0)
        self.UDPSender = UDPSender()

    # sends a message to one specific elevator.
    def sendToOne(self, peer, message):
        self.TCPSender.send(peer.IP, message)

    # Sends messages to all the elevators registered in this instance.
    def sendToAll(self, peerList, message):
        for peer in peerList:
            self.sendToOne(peer, message)

    # broadcasts messages on UDP, do not expect that It will arrive.
    def broadcast(self, message):
        self.UDPSender.send(message)
Ejemplo n.º 2
0
class Communicator():
    def __init__(self, messageHandler):

        # the tcp listener, that handles incoming connections on tcp.
        self.TCPReceiver = TCPReceiver("", 0, messageHandler)
        self.TCPReceiver.start()

        # the udp listener that gets broadcasting messages.
        self.UDPReceiver = UDPReceiver(6005, messageHandler)
        self.UDPReceiver.start()

        # the tcp and udp senders.
        self.TCPSender = TCPSender("", 0)
        self.UDPSender = UDPSender()

    # sends a message to one specific elevator.
    def sendToOne(self, peer, message):
        self.TCPSender.send(peer.IP, pickle.dumps(message))

    # Sends messages to all the elevators registered in this instance.
    def sendToAll(self, peerList, message):
        for peer in peerList:
            self.sendToOne(peer, message)

    # broadcasts messages on UDP, do not expect that It will arrive.
    def broadcast(self, message):
        self.UDPSender.send(pickle.dumps(message))
Ejemplo n.º 3
0
    def __init__(self, messageHandler):

        # the tcp listener, that handles incoming connections on tcp.
        self.TCPReceiver = TCPReceiver("", 0, messageHandler)
        self.TCPReceiver.start()

        # the udp listener that gets broadcasting messages.
        self.UDPReceiver = UDPReceiver(6005, messageHandler)
        self.UDPReceiver.start()

        # the tcp and udp senders.
        self.TCPSender = TCPSender("", 0)
        self.UDPSender = UDPSender()
Ejemplo n.º 4
0
    def __init__(self, messageHandler):

        # the tcp listener, that handles incoming connections on tcp.
        self.TCPReceiver = TCPReceiver("129.241.187.145", 0, messageHandler)
        self.TCPReceiver.start()

        # the udp listener that gets broadcasting messages.
        self.UDPReceiver = UDPReceiver(6005, messageHandler)
        self.UDPReceiver.start()

        # the tcp and udp senders.
        self.TCPSender = TCPSender("129.241.187.145", 0)
        self.UDPSender = UDPSender()
Ejemplo n.º 5
0
    def sendFilesAdvanced(self, ftp):
        self.archiveManager.stopArchiving()
        self.recordingManager.stopRecording()
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.settimeout(20)
        sock.bind(("", 0))
        #use udpReceiver to get messages from advanced FTP server
        udpReceiver = UDPReceiver(sock, self.logger)
        try:
            canConnect = False
            while not canConnect:
                #asking to start sending files
                self.sendUDPMsg("request_connect " + self.piName, sock)
                if not self.serverIsAlive(ftp):
                    break
                time.sleep(5)
                msg = udpReceiver.getMsg().split(" ")
                if msg[0] != "":
                    if len(msg) < 2:
                        self.logger.log(
                            "[FTPConnector] received unrecognized message: " +
                            str(msg))
                    elif msg[0] == "connect" and msg[1] == self.piName:
                        #response was we can start sending files
                        self.logger.log(
                            "[FTPConnector] Ready to start transfer!")
                        canConnect = True
                        self.sendAlive = True
                        #start sending alive requests because we are transferring now
                        threading.Thread(target=self.sendAliveMsg,
                                         args=([sock])).start()
                    elif msg[0] == "no_connect" and msg[1] == self.piName:
                        #response was we cannot send files yet
                        self.logger.log("[FTPConnector] Not ready to transfer")
                    else:
                        self.logger.log(
                            "[FTPConnector] received unrecognized message: " +
                            str(msg))

            if canConnect:
                #we have the goahead to send files now
                self.sendUDPMsg(
                    "message " + self.piName +
                    " is starting to transfer data!", sock)
                #backup text files so we can send them over along with tar files
                #this is done right before transfer so we can send a relatively recent log file to the FTP server
                self.backupTextFiles()
                #gets the filenames of all the files in the backup folder
                filesToSend = self.getBackupFilenames()
                #these are used to tell the user of the FTP server how many files we have left to transfer
                count = 0
                total = len(filesToSend)
                #set the checkInterval to 900 seconds because we don't want to reconnect to the FTP server immidiately
                #after we are done sending data to it. It will be set back to 10 seconds if any errors occur in the transer
                self.checkInterval = 900
                for f in filesToSend:
                    count += 1
                    fullPath = os.path.join(self.backupFolder, f)
                    try:
                        if not self.serverIsAlive(ftp):
                            #server must have disconnected!
                            self.logger.log(
                                "[FTPConnector] Server unexpectedly disconnected, stopping transer"
                            )
                            self.checkInterval = 10
                            break
                        #gets the size of the file we are about to send
                        fileSizeMB = " (" + "{0:.2f}".format(
                            float(os.path.getsize(fullPath)) /
                            (1024**2)) + "MB)"
                        #sends a message to the FTP server to let the user know what file we are transferring
                        self.sendUDPMsg(
                            "message " + self.piName + " is sending file " +
                            str(count) + " of " + str(total) + ": " + str(f) +
                            fileSizeMB, sock)
                        self.logger.log(
                            "[FtpConnector] Attempting to send file: " +
                            fullPath)
                        #attempt to send file
                        ftp.storbinary("STOR " + f, open(fullPath, "rb"))
                        self.logger.log(
                            "[FtpConnector] Successfully sent file: " +
                            fullPath)
                        subprocess.call(["sudo", "rm", fullPath])
                        self.logger.log(
                            "[FtpConnector] Successfully deleted file: " +
                            fullPath)
                    except Exception as e:
                        #something went wrong with a file transfer if we are here. We will still attempt to send the
                        #rest of the files in out backup directory though
                        self.checkInterval = 10
                        self.logger.logError(
                            "FtpConnector",
                            "Error with file transfer of " + fullPath, e)
                #send messages to let the ftp server know we are done transferring now
                self.sendUDPMsg(
                    "message " + self.piName + " is done transferring files",
                    sock)
                self.sendUDPMsg("done " + self.piName, sock)
        except Exception as e:
            #if we end up here, something went wrong with the entire transfer. We do not attempt to send
            #any more files to this instance of the FTP connection
            self.checkInterval = 10
            self.logger.logError("FtpConnector", "Error with file transfer", e)
        #cleans up after sending files. Starts recording and archiving threads again, and stops keep alive messages
        self.sendAlive = False
        udpReceiver.stop()
        self.recordingManager.startRecording()
        self.archiveManager.startArchiving()
Ejemplo n.º 6
0
	def sendFilesAdvanced(self, ftp):
		self.archiveManager.stopArchiving()
		self.recordingManager.stopRecording()
		sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		sock.settimeout(20)
		sock.bind(("", 0))
		#use udpReceiver to get messages from advanced FTP server
		udpReceiver = UDPReceiver(sock, self.logger)
		try:
			canConnect = False
			while not canConnect:
				#asking to start sending files
				self.sendUDPMsg("request_connect " + self.piName, sock)
				if not self.serverIsAlive(ftp):
					break
				time.sleep(5)
				msg = udpReceiver.getMsg().split(" ")
				if msg[0] != "":
					if len(msg) < 2:
						self.logger.log("[FTPConnector] received unrecognized message: " + str(msg))
					elif msg[0] == "connect" and msg[1] == self.piName:
						#response was we can start sending files
						self.logger.log("[FTPConnector] Ready to start transfer!")
						canConnect = True
						self.sendAlive = True
						#start sending alive requests because we are transferring now
						threading.Thread(target = self.sendAliveMsg, args = ([sock])).start()
					elif msg[0] == "no_connect" and msg[1] == self.piName:
						#response was we cannot send files yet
						self.logger.log("[FTPConnector] Not ready to transfer")
					else:
						self.logger.log("[FTPConnector] received unrecognized message: " + str(msg))
					
			if canConnect:
				#we have the goahead to send files now
				self.sendUDPMsg("message " + self.piName + " is starting to transfer data!", sock)
				#backup text files so we can send them over along with tar files
				#this is done right before transfer so we can send a relatively recent log file to the FTP server
				self.backupTextFiles()
				#gets the filenames of all the files in the backup folder
				filesToSend = self.getBackupFilenames()
				#these are used to tell the user of the FTP server how many files we have left to transfer
				count = 0
				total = len(filesToSend)
				#set the checkInterval to 900 seconds because we don't want to reconnect to the FTP server immidiately
				#after we are done sending data to it. It will be set back to 10 seconds if any errors occur in the transer
				self.checkInterval = 900
				for f in filesToSend:
					count += 1
					fullPath = os.path.join(self.backupFolder,f)
					try:
						if not self.serverIsAlive(ftp):
							#server must have disconnected!
							self.logger.log("[FTPConnector] Server unexpectedly disconnected, stopping transer")
							self.checkInterval = 10
							break
						#gets the size of the file we are about to send
						fileSizeMB = " ("+"{0:.2f}".format(float(os.path.getsize(fullPath))/(1024**2))+"MB)"
						#sends a message to the FTP server to let the user know what file we are transferring
						self.sendUDPMsg("message " + self.piName + " is sending file " + str(count) + " of " + str(total) + ": " + str(f) + fileSizeMB, sock)
						self.logger.log("[FtpConnector] Attempting to send file: " + fullPath)
						#attempt to send file
						ftp.storbinary("STOR " + f, open(fullPath, "rb"))
						self.logger.log("[FtpConnector] Successfully sent file: " + fullPath)
						subprocess.call(["sudo", "rm", fullPath])
						self.logger.log("[FtpConnector] Successfully deleted file: " + fullPath)
					except Exception as e:
						#something went wrong with a file transfer if we are here. We will still attempt to send the
						#rest of the files in out backup directory though
						self.checkInterval = 10
						self.logger.logError("FtpConnector", "Error with file transfer of " + fullPath, e)
				#send messages to let the ftp server know we are done transferring now
				self.sendUDPMsg("message " + self.piName + " is done transferring files", sock)
				self.sendUDPMsg("done " + self.piName, sock)
		except Exception as e:
			#if we end up here, something went wrong with the entire transfer. We do not attempt to send
			#any more files to this instance of the FTP connection
			self.checkInterval = 10
			self.logger.logError("FtpConnector", "Error with file transfer", e)
		#cleans up after sending files. Starts recording and archiving threads again, and stops keep alive messages
		self.sendAlive = False
		udpReceiver.stop()
		self.recordingManager.startRecording()
		self.archiveManager.startArchiving()