|
| 1 | +import time |
| 2 | +import socketserver |
| 3 | +from pymycobot.mycobot import MyCobot |
| 4 | +import numpy as np |
| 5 | + |
| 6 | + |
| 7 | +class TCPMessageHandler(socketserver.StreamRequestHandler): |
| 8 | + |
| 9 | + def handle(self): |
| 10 | + """ |
| 11 | + Process socket data |
| 12 | +
|
| 13 | + """ |
| 14 | + # process received data. |
| 15 | + while True: |
| 16 | + try: |
| 17 | + # data=bytes.decode(self.rfile.readline().strip()) |
| 18 | + data = bytes.decode(self.request.recv(1024)) |
| 19 | + print(data) |
| 20 | + except Exception as ex: |
| 21 | + print(ex) |
| 22 | + return |
| 23 | + |
| 24 | + data = data.split(',') |
| 25 | + commend = [] |
| 26 | + |
| 27 | + for dt in data: |
| 28 | + try: |
| 29 | + if dt.isdigit(): |
| 30 | + commend.append(int(dt)) |
| 31 | + else: |
| 32 | + commend.append(float(dt)) |
| 33 | + except ValueError: |
| 34 | + commend.append(None) |
| 35 | + |
| 36 | + if len(commend) > 0: |
| 37 | + print("Received:%s" % commend) |
| 38 | + self.request.sendall(str.encode(str(commend))) |
| 39 | + |
| 40 | + |
| 41 | +class SocketServer(object): |
| 42 | + def __init__(self, host, port): |
| 43 | + super().__init__() |
| 44 | + self.host = host |
| 45 | + self.port = port |
| 46 | + |
| 47 | + def start_server(self): |
| 48 | + while True: |
| 49 | + try: |
| 50 | + server = socketserver.TCPServer((self.host, self.port), |
| 51 | + TCPMessageHandler) |
| 52 | + break |
| 53 | + except: |
| 54 | + time.sleep(1) |
| 55 | + continue |
| 56 | + try: |
| 57 | + print("server open seccess") |
| 58 | + server.serve_forever() |
| 59 | + |
| 60 | + finally: |
| 61 | + print("server close") |
| 62 | + server.server_close() |
| 63 | + |
| 64 | + |
| 65 | +class Robot(object): |
| 66 | + def __init__(self, serial, baud): |
| 67 | + super().__init__() |
| 68 | + self.serial = serial |
| 69 | + self.baud = baud |
| 70 | + |
| 71 | + def start_Robot(self): |
| 72 | + try: |
| 73 | + mc = MyCobot(self.serial, self.baud) # 树莓派版本打开机械臂,串口固定,无需USB连接 |
| 74 | + print(mc) # 打印机械臂端口信息 |
| 75 | + except: |
| 76 | + print("can not find cobot") |
| 77 | + exit(0) |
| 78 | + |
| 79 | + |
| 80 | +if __name__ == "__main__": |
| 81 | + host = '192.168.10.191' # 输入本机IP地址 |
| 82 | + port = 9000 |
| 83 | + serial = '' |
| 84 | + baud = 1000000 |
| 85 | + server = SocketServer(host, port) # 声明服务器端口 |
| 86 | + mycobot = Robot(serial, baud) # 声明机械臂接口 |
| 87 | + server.start_server() # 永久打开服务器 |
0 commit comments