def main(): while True: myMinion = ClientSocket() myMinion.host = 'localhost' myMinion.port = 2391 myMinion.Create() if myMinion.socket and myMinion.alive: myMinion.Resolve() if myMinion.socket and myMinion.alive: myMinion.Connect() if myMinion.socket and myMinion.alive: myMinion.SendData('main_session\r\n') #if myMinion.socket and myMinion.alive: # myMinion.SendData('contact_list\r\n') if myMinion.socket and myMinion.alive: while True and myMinion.alive: data = myMinion.ReceiveData() #print "Debug data rx: " + str(data) result = parseCommand(data) if result != -1 and result != None: myMinion.SendData(str(result)) # if gets out of this while, then it means socket is broken, so wait 30 seconds and try to # reconnect. if myMinion.socket: myMinion.Close() time.sleep(10)
def __init__(self): # tiles and pixels self._tile_width = ConstantVariables.TILE_WIDTH self._nb_tile_x = ConstantVariables.NB_COLUMN self._nb_tile_y = ConstantVariables.NB_ROW self._width_px = ConstantVariables.WINDOW_WIDTH self._height_px = ConstantVariables.WINDOW_HEIGHT # elements # screen - textures self._screen = pygame.display.set_mode( (self._width_px, self._height_px)) self._background = pygame.image.load('../assets/grass.jpg') self._background = pygame.transform.scale( self._background, (self._width_px, self._height_px)) self._apple_image = pygame.image.load('../assets/apple.png') self._apple_image = pygame.transform.scale( self._apple_image, (self._tile_width, self._tile_width)) # game self._game = GameServer() # socket self._socket = ClientSocket() # other self._running = True self._my_direction = "not_set"
def sendEvent(self, data): while self._sock.sendAction(data) == False: try: print("reconnect...", self._host, self._port) self._sock.close() self._sock = ClientSocket() self.bindSocket(self._host, self._port) except: time.sleep(4)
def handleConnectionRequest(self): """ Permet de gérer une demande de connexion au serveur :return: :rtype: None """ (clientSocket, (addr, port)) = self.welcomeSocket.accept() clientSocket.setblocking(0) self.inputs += [clientSocket] address = "{:s}:{:d}".format(addr, port) self.clients[clientSocket] = ClientSocket(address) print("> [+] New connection socket opened for {:s}".format(address))
def main(): clearScreen() # will be the control socket to send over commands clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client = ClientSocket(sys.argv[1], (int)(sys.argv[2]), clientSocket) connected = client.connect() while client.connected: command, response = handleInput() if command is not COMMANDS.UNDEFINED: # organize commands to get sent to server info = {'command': command, 'file_name': response[1] if len(response) is 2 else ""} client.send(info) # Time to kill the control connection. Tell serve to close connection and we close too if command is COMMANDS.QUIT: client.close() print "Closing connection... Quiting..." exit() # We got more stuff incoming from the server to handle the commands we requested # Open up new connection for the data channel else: # server replied to the client's command request data_info = client.recv() if command is COMMANDS.LS: for i in data_info['data']: print i elif command is COMMANDS.PUT: # Server ready for file transfer if data_info['status'] in 'success': # Before we send lets make sure the file exis if os.path.isfile(info['file_name']): # Read file to send to server with open(info['file_name'], 'r') as infile: data_info['status'] = 'success' data_info['data'] = infile.read() data_info['file_length'] = len(data_info['data']) client.send(data_info) # Did it successfully send data_info = client.recv() if data_info['status'] in 'success': # any changes? if data_info['changes'] not in '': print 'Server modified file: %s' % (data_info['changes']) # File doesn't exist else: # Let server know to ignore file transfer data_info = {'status': 'No file'} client.send(data_info) print "File does not exist" else: print "Server is busy" elif command is COMMANDS.GET: if data_info['status'] in 'success': with open(info['file_name'], 'w') as outfile: outfile.write(data_info['data']) print 'Success delivery' print '%s ~%i bytes' %(info['file_name'], data_info['file_length']) else: print 'Error: ', data_info['status'] else: print "Unknown command"
from ClientSocket import ClientSocket import time import sys as s IP = '10.200.50.10' PORT = 5010 client = ClientSocket(IP, PORT) if len(s.argv) < 2: print("No args, default used") client.sendData( "This was a triumph. I'm making a note here, huge success.") if len(s.argv) >= 2: for s in s.argv[1:]: client.sendData(str(s)) time.sleep(2) time.sleep(1) client.killSocket()
class App(tk.Tk): def __init__(self,*args,**kwargs): tk.Tk.__init__(self,*args,**kwargs) self.setup=tk.Button(self,text="Setup",command=self.setupFunc) self.setup.pack() self.play=tk.Button(self,text="Play",command=self.playFunc) self.play.pack() self.pause=tk.Button(self,text="Pause",command=self.pauseFunc) self.pause.pack() self.teardown=tk.Button(self,text="Teardown",command=self.teardownFunc) self.teardown.pack() self.img=ImageTk.PhotoImage(Image.open('tuned.jpg')) self.video=tk.Label(self,image=self.img) self.video.pack() self.status="INIT" self.c=0 self.initialize() def initialize(self): self.s_addr=sys.argv[1] self.s_port=sys.argv[2] self.server_address=(self.s_addr,int(self.s_port)) self.client=ClientSocket(self.server_address) def setupFunc(self): if self.status=="INIT": self.status="READY" self.client.send("setup") rcvd=self.client.receive() print " Response received from server:"+rcvd def teardownFunc(self): self.status="INIT" self.client.send("teardown") self.client.close() print " Connection closed successfully" def playFunc(self): print "Started receiving frame..." self.status="PLAYING" self.client.send("play") self.playUtil(); def playUtil(self): path=self.client.receive_frame(self.c,self) self.img=ImageTk.PhotoImage(Image.open(path)) self.video.configure(image=self.img) self.c+=1 os.remove(path) self.after(50, self.playUtil) def pauseFunc(self): if self.status=="PLAYING": print " Video paused for a while...." self.status="READY" self.client.send("pause")
def initialize(self): self.s_addr=sys.argv[1] self.s_port=sys.argv[2] self.server_address=(self.s_addr,int(self.s_port)) self.client=ClientSocket(self.server_address)
class GameClient: def __init__(self): # tiles and pixels self._tile_width = ConstantVariables.TILE_WIDTH self._nb_tile_x = ConstantVariables.NB_COLUMN self._nb_tile_y = ConstantVariables.NB_ROW self._width_px = ConstantVariables.WINDOW_WIDTH self._height_px = ConstantVariables.WINDOW_HEIGHT # elements # screen - textures self._screen = pygame.display.set_mode( (self._width_px, self._height_px)) self._background = pygame.image.load('../assets/grass.jpg') self._background = pygame.transform.scale( self._background, (self._width_px, self._height_px)) self._apple_image = pygame.image.load('../assets/apple.png') self._apple_image = pygame.transform.scale( self._apple_image, (self._tile_width, self._tile_width)) # game self._game = GameServer() # socket self._socket = ClientSocket() # other self._running = True self._my_direction = "not_set" def play(self): # create connection self._socket.connect() while self._running: self.manage_event() # ask to the server for receive game data # if the client has lost : this method return None self._game = self._socket.send_direction_and_get_data( self._my_direction) if self._game is None: self._running = False break self.draw_screen() # update display pygame.display.flip() time.sleep(0.05) def manage_event(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self._running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_w or event.key == pygame.K_UP: self._my_direction = Direction.UP.value elif event.key == pygame.K_a or event.key == pygame.K_LEFT: self._my_direction = Direction.LEFT.value elif event.key == pygame.K_s or event.key == pygame.K_DOWN: self._my_direction = Direction.DOWN.value elif event.key == pygame.K_d or event.key == pygame.K_RIGHT: self._my_direction = Direction.RIGHT.value def draw_screen(self): # background self._screen.blit(self._background, (0, 0)) # draw apple rect_apple = self._apple_image.get_rect() rect_apple.x = self._game.apple.get_coordinate( )[0] * ConstantVariables.TILE_WIDTH rect_apple.y = self._game.apple.get_coordinate( )[1] * ConstantVariables.TILE_WIDTH self._screen.blit(self._apple_image, rect_apple) # draw snakes for snake in self._game.snakes: # head head_coordinate = snake.get_head_coordinate() rect = pygame.Rect(head_coordinate[0] * self._tile_width, head_coordinate[1] * self._tile_width, self._tile_width, self._tile_width) if snake.id_client == self._socket.id: pygame.draw.rect(self._screen, GREEN, rect) else: pygame.draw.rect(self._screen, RED, rect) # body for part in snake.body_coordinates: rect = pygame.Rect(part[0] * self._tile_width, part[1] * self._tile_width, self._tile_width, self._tile_width) pygame.draw.rect(self._screen, GREY, rect)
def __init__(self, anActivity, IP, port) : self.socket = ClientSocket(self, IP, port, anActivity) self.socket.connect((IP, port)) self.lock = threading.Lock()
class DataManagement(object): """ Class constructor which provides connection to an M-START Server - anActivity(String): the Activity name as it is set in the M-START Server database - IP(String): the M-START Server IP address - port(int): the M-Start Server port """ def __init__(self, anActivity, IP, port) : self.socket = ClientSocket(self, IP, port, anActivity) self.socket.connect((IP, port)) self.lock = threading.Lock() """ This method is called when a message from the M-START Server is received. It has to be implemented in an other class extending from DataManagement in order to treat the messages received. Note: you can re-implement this method if you want to handle the messages here. """ def messageReceived(self,aMessage) : print("No treatment defined for messages received") """ Send a message to the M-START Server. - aMessage(OSCMessage): the message to send """ def sendMessage(self,aMessage) : self.socket.sendOSC(aMessage) """ Send a message to the M-START Server. - address(String): the address of the OSCMessage - value: the value of the OSCMessage """ def sendMessageTo(self, address, value) : oscmsg = OSCMessage() oscmsg.setAddress(address) oscmsg.append(value) self.socket.sendOSC(oscmsg) """ Send a message to the M-START M-START Server - address(String): the address of the OSC message - listvalue : the list of OSCMessage's values """ def sendMessageWithListValueTo(self, address, listvalue) : oscmsg = OSCMessage() oscmsg.setAddress(address) for value in listvalue : oscmsg.append(value) self.socket.sendOSC(oscmsg) """ Ends the connection with the M-START Server """ def close(self) : self.socket.close() ; """ This method is called by PiManager to notify that a gpio has been rising or falling It has to be implemented in an other class extending from DataManagement in order to treat the messages received. - id(int) : the id of the gpio - rising(bool) : True if the gpio has been rising and False else Note: you can re-implement this method if you want to handle the messages here. """ def gpioEvent(self, id, rising) : print("No treatment defined for gpio events")
def __init__(self, parent=None): super().__init__(None) self._host = "" self._port = 0 self._cam = WebCamView(self) self._up_left = QPushButton("↖", self) self._up = QPushButton("↑", self) self._up_right = QPushButton("↗", self) self._mid_left = QPushButton("←", self) self._mid = QPushButton("", self) self._mid_right = QPushButton("→", self) self._down_left = QPushButton("↙", self) self._down = QPushButton("↓", self) self._down_right = QPushButton("↘", self) btn_grp = [self._up_left, self._up, self._up_right, self._mid_left, self._mid, self._mid_right, self._down_left, self._down, self._down_right] press_event = [self.upLeftPressEvent, self.upPressEvent, self.upRightPressEvent, self.midLefPressEvent, self.midPressEvent, self.midRightPressEvent, self.downLeftPressEvent, self.downPressEvent, self.downRightPressEvent] release_event = [self.upLeftReleaseEvent, self.upReleaseEvent, self.upRightReleaseEvent, self.midLeftReleaseEvent, self.midReleaseEvent, self.midRightReleaseEvent, self.downLeftReleaseEvent, self.downReleaseEvent, self.downRightReleaseEvent] # set position and connect event p = QPoint(620, 420) # start point for i in range(len(btn_grp)): btn_grp[i].setFixedSize(QSize(50, 50)) btn_grp[i].move(p) btn_grp[i].pressed.connect(press_event[i]) btn_grp[i].released.connect(release_event[i]) btn_grp[i].setFocusPolicy(Qt.NoFocus) if p.x() >= 740: p.setX(620) p.setY(p.y()+60) else: p.setX(p.x()+60) #act = QAction("Action", self._up_left, ) #self._up_left.setShortcut(Qt.Key_Up) #self._up_left.shortcut = QShortcut(QKeySequence("Ctrl+Q"), self) #self._up_left.shortcut.activated.connect(self.) #self._up_left.setAutoRepeat(False) #self._up_left.addAction() #self._up.clicked.connect(self.send_event) #self._graphic = QOpenGLWidget(self) #self._graphic.setFixedSize(QSize(500, 400)) #self._graphic.move(QPoint(10, 10)) self._cam.setFixedSize(QSize(500, 400)) self._cam.move(QPoint(10, 10)) #self._layout = QGridLayout(self) #self._layout.addWidget(self._up) #self._layout.addWidget(self._down) #self.setLayout(self._layout) self.setWindowTitle("RaspCar Windows Controller") self.setFixedSize(800, 600) self._sock = ClientSocket()
class ControlWindow(QWidget): def __init__(self, parent=None): super().__init__(None) self._host = "" self._port = 0 self._cam = WebCamView(self) self._up_left = QPushButton("↖", self) self._up = QPushButton("↑", self) self._up_right = QPushButton("↗", self) self._mid_left = QPushButton("←", self) self._mid = QPushButton("", self) self._mid_right = QPushButton("→", self) self._down_left = QPushButton("↙", self) self._down = QPushButton("↓", self) self._down_right = QPushButton("↘", self) btn_grp = [self._up_left, self._up, self._up_right, self._mid_left, self._mid, self._mid_right, self._down_left, self._down, self._down_right] press_event = [self.upLeftPressEvent, self.upPressEvent, self.upRightPressEvent, self.midLefPressEvent, self.midPressEvent, self.midRightPressEvent, self.downLeftPressEvent, self.downPressEvent, self.downRightPressEvent] release_event = [self.upLeftReleaseEvent, self.upReleaseEvent, self.upRightReleaseEvent, self.midLeftReleaseEvent, self.midReleaseEvent, self.midRightReleaseEvent, self.downLeftReleaseEvent, self.downReleaseEvent, self.downRightReleaseEvent] # set position and connect event p = QPoint(620, 420) # start point for i in range(len(btn_grp)): btn_grp[i].setFixedSize(QSize(50, 50)) btn_grp[i].move(p) btn_grp[i].pressed.connect(press_event[i]) btn_grp[i].released.connect(release_event[i]) btn_grp[i].setFocusPolicy(Qt.NoFocus) if p.x() >= 740: p.setX(620) p.setY(p.y()+60) else: p.setX(p.x()+60) #act = QAction("Action", self._up_left, ) #self._up_left.setShortcut(Qt.Key_Up) #self._up_left.shortcut = QShortcut(QKeySequence("Ctrl+Q"), self) #self._up_left.shortcut.activated.connect(self.) #self._up_left.setAutoRepeat(False) #self._up_left.addAction() #self._up.clicked.connect(self.send_event) #self._graphic = QOpenGLWidget(self) #self._graphic.setFixedSize(QSize(500, 400)) #self._graphic.move(QPoint(10, 10)) self._cam.setFixedSize(QSize(500, 400)) self._cam.move(QPoint(10, 10)) #self._layout = QGridLayout(self) #self._layout.addWidget(self._up) #self._layout.addWidget(self._down) #self.setLayout(self._layout) self.setWindowTitle("RaspCar Windows Controller") self.setFixedSize(800, 600) self._sock = ClientSocket() def __del__(self): self._sock.close() def bindSocket(self, host, port): self._host = host self._port = port return self._sock.connect(host, port) def sendEvent(self, data): while self._sock.sendAction(data) == False: try: print("reconnect...", self._host, self._port) self._sock.close() self._sock = ClientSocket() self.bindSocket(self._host, self._port) except: time.sleep(4) """ def event(self, e): if type(e) == QKeyEvent and not e.isAutoRepeat(): if e.key() == Qt.Key_Up: print("123") return True #print(type(e)) return QWidget.event(self, e) """ def keyPressEvent(self, e): if not e.isAutoRepeat(): obj = None if e.key() == Qt.Key_Up: obj = self._up elif e.key() == Qt.Key_Left: obj = self._mid_left elif e.key() == Qt.Key_Right: obj = self._mid_right elif e.key() == Qt.Key_Down: obj = self._down if obj != None: obj.setDown(True) obj.pressed.emit() else: QWidget.keyPressEvent(self, e) else: QWidget.keyPressEvent(self, e) def keyReleaseEvent(self, e): if not e.isAutoRepeat(): obj = None if e.key() == Qt.Key_Up: obj = self._up elif e.key() == Qt.Key_Left: obj = self._mid_left elif e.key() == Qt.Key_Right: obj = self._mid_right elif e.key() == Qt.Key_Down: obj = self._down if obj != None: obj.setDown(False) obj.released.emit() else: QWidget.keyPressEvent(self, e) else: QWidget.keyReleaseEvent(self, e) #press function def upLeftPressEvent(self): pass def upPressEvent(self): print("up press") self.sendEvent("arrow-key:up action:press") pass def upRightPressEvent(self): pass def midLefPressEvent(self): print("mid-left press") self.sendEvent("arrow-key:mid-left action:press") pass def midPressEvent(self): pass def midRightPressEvent(self): print("mid-right press") self.sendEvent("arrow-key:mid-right action:press") pass def downLeftPressEvent(self): pass def downPressEvent(self): print("down press") self.sendEvent("arrow-key:down action:press") pass def downRightPressEvent(self): pass #release function def upLeftReleaseEvent(self): pass def upReleaseEvent(self): print("up release") self.sendEvent("arrow-key:up action:release") pass def upRightReleaseEvent(self): pass def midLeftReleaseEvent(self): print("mid-left release") self.sendEvent("arrow-key:mid-left action:release") pass def midReleaseEvent(self): pass def midRightReleaseEvent(self): print("mid-right release") self.sendEvent("arrow-key:mid-right action:release") pass def downLeftReleaseEvent(self): pass def downReleaseEvent(self): print("down release") self.sendEvent("arrow-key:down action:release") pass def downRightReleaseEvent(self): print("send fake close") self.sendEvent("close") pass
from ClientSocket import ClientSocket from threading import Thread from threading import Timer import cv2 as cv import maestro import numpy as np import mpmath import time from picamera import PiCamera from picamera.array import PiRGBArray #Variables IP = '10.200.8.58' PORT = 5010 client = ClientSocket(IP, PORT) waitTime = 3 left = False lossTime = 0 prevFaceFound = False centerStep = 200 centerXThresh = 25 centerYThresh = 25 faceDistTarget = 12 ANGULAR_VELOCITY = 2000 VELOCITY = 0.2 headX = 6000 headY = 6000 HEADTILT = 4 HEADTURN = 3 WAIST = 0 TURN = 2