1#! /usr/bin/env python 2""" Human control with keyboard through sockets 3 4this example is meant to show how to use services with sockets. 5After the connection with the socket, we just send a message well formed. 6You can control the human with the numpad : 8 and 5 for forward and backward, 7and 4 and 6 for left and right. 8 9""" 10 11import sys 12import socket 13import tty, termios 14 15HOST = '127.0.0.1' 16PORT = 4000 17 18def getchar(): 19 """ Returns a single character from standard input """ 20 21 fd = sys.stdin.fileno() 22 old_settings = termios.tcgetattr(fd) 23 try: 24 tty.setraw(sys.stdin.fileno()) 25 ch = sys.stdin.read(1) 26 finally: 27 termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) 28 return ch 29 30 31def _connect_port(port): 32 """ Establish the connection with the given MORSE port""" 33 sock = None 34 35 for res in socket.getaddrinfo(HOST, port, socket.AF_UNSPEC, socket.SOCK_STREAM): 36 af, socktype, proto, canonname, sa = res 37 try: 38 sock = socket.socket(af, socktype, proto) 39 except socket.error: 40 sock = None 41 continue 42 try: 43 sock.connect(sa) 44 except socket.error: 45 sock.close() 46 sock = None 47 continue 48 break 49 50 return sock 51 52def main(): 53 sock = _connect_port(PORT) 54 if not sock: 55 sys.exit(1) 56 57 print("sock connected") 58 print("Please press q to quit and use 8456 to move") 59 esc = 0 60 _id = 0 61 62 while not esc: 63 c = getchar() 64 speed = 0 65 rot = 0 66 if (c == "8"): 67 speed = 0.1 68 elif (c == "5"): 69 speed = -0.1 70 elif (c == "4"): 71 rot = 0.1 72 elif (c == "6"): 73 rot = -0.1 74 if (speed != 0 or rot != 0): 75 data_out = "id%d human move [%f, %f]\n" % (_id, speed, rot) 76 sent = sock.send(data_out) 77 print ("SENT DATA (%d bytes): %s" % (sent, data_out)) 78 _id = _id + 1 79 80 if c == "q": 81 esc = 1 82 83 sock.close() 84 print("\nBye bye!") 85 86main() 87