控制机器臂

    1. import socket
    2. import sys
    3. received_count: int = 0
    4. def getCmdStr(cmd):
    5. if cmd == '011':
    6. return "00 00 00 00 00 06 01 05 00 00 FF 00"
    7. elif cmd == '012':
    8. return "00 00 00 00 00 06 01 05 00 00 00 00"
    9. elif cmd == '021':
    10. return "00 00 00 00 00 06 01 05 00 01 FF 00"
    11. elif cmd == '022':
    12. return "00 00 00 00 00 06 01 05 00 01 00 00"
    13. elif cmd == "031":
    14. return "00 00 00 00 00 06 01 05 00 02 FF 00"
    15. elif cmd == '032':
    16. return "00 00 00 00 00 06 01 05 00 02 00 00"
    17. elif cmd == '121':
    18. return "00 00 00 00 00 06 01 05 00 11 FF 00"
    19. elif cmd == '122':
    20. return "00 00 00 00 00 06 01 05 00 11 00 00"
    21. else:
    22. return "fail"
    23. def start_tcpClient(ip, port,cmd):
    24. ###create socket
    25. client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    26. failed_count = 0
    27. while True:
    28. try:
    29. print("start connect to server")
    30. client.connect((ip, port))
    31. break
    32. except socket.error:
    33. failed_count += 1
    34. print("fail to connect to server %d times" % failed_count)
    35. if failed_count == 10: return
    36. ###send comand
    37. # print("connect success")
    38. # print("011:打开1#口") # :00 00 00 00 00 06 01 05 00 01 FF 00
    39. # print("012:关闭1#口") # :00 00 00 00 00 06 01 05 00 01 00 00
    40. # print("021:打开2#口") # :00 00 00 00 00 06 01 05 00 02 FF 00
    41. # print("022:关闭2#口") # :00 00 00 00 00 06 01 05 00 02 00 00
    42. # print("121:打开12#口") # :00 00 00 00 00 06 01 05 00 0C FF 00
    43. # print("122:关闭12#口") # :00 00 00 00 00 06 01 05 00 0C 00 00
    44. cmdstr = getCmdStr(cmd)#获得代码
    45. if cmdstr == "fail":
    46. print("wrong comand", cmd)
    47. else:
    48. d = bytes.fromhex(cmdstr)
    49. client.send(d)
    50. print("send message:", cmdstr)
    51. recvMsg = client.recv(1024)
    52. print("receive message:", recvMsg)
    53. print("recv len is :[%d]" % len(recvMsg))
    54. ###received_count+=1
    55. client.close()
    56. start_tcpClient('192.168.0.12', 502,"012")
    57. # received_data = client.recv(1024)
    58. # received_size = len(received_data)
    59. # print("cmd res receive message:",received_data)
    60. # print("cmd res receive done......",received_size)