2025-07-29 13:16:30 +08:00
|
|
|
import json
|
|
|
|
|
import logging
|
|
|
|
|
import socket
|
|
|
|
|
import threading
|
|
|
|
|
import time
|
|
|
|
|
import random
|
|
|
|
|
|
|
|
|
|
import Constant
|
|
|
|
|
from Util.util_log import log
|
|
|
|
|
|
|
|
|
|
class TCPClient:
|
|
|
|
|
def __init__(self, ip, port):
|
|
|
|
|
self.error_count=0
|
|
|
|
|
self.IPAddress = ip
|
|
|
|
|
self.port = port
|
|
|
|
|
self.thread_signal = True
|
|
|
|
|
self.connected = False
|
|
|
|
|
self.client_socket = None
|
|
|
|
|
|
|
|
|
|
def CreatConnect(self):
|
|
|
|
|
if self.client_socket:
|
|
|
|
|
self.client_socket.close()
|
|
|
|
|
self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
|
|
|
self.client_socket.settimeout(5)
|
|
|
|
|
self.client_socket.connect((self.IPAddress, self.port))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def is_Connect(self):
|
|
|
|
|
try:
|
|
|
|
|
self.client_socket.send(b'')
|
|
|
|
|
return True
|
|
|
|
|
except OSError:
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def run(self):
|
|
|
|
|
while self.thread_signal:
|
|
|
|
|
time.sleep(0.4)
|
|
|
|
|
self.connected = (self.error_count <= 3)
|
|
|
|
|
try:
|
|
|
|
|
if (self.send_Status() and self.send_Command()):
|
|
|
|
|
self.error_count = 0
|
|
|
|
|
except Exception as e:
|
2025-10-24 10:29:00 +08:00
|
|
|
log.log_message(logging.ERROR,f'COM_TCP: {str(e)}')
|
2025-07-29 13:16:30 +08:00
|
|
|
self.error_count += 1
|
|
|
|
|
if self.error_count> 5:
|
2025-09-10 09:16:57 +08:00
|
|
|
print("Error: 机械臂控制程序中TCPClient is not connected")
|
2025-11-08 20:38:55 +08:00
|
|
|
# log.log_message(logging.ERROR,f'{Constant.str_tcp_connect_no_reply}:{str(e)}')
|
2025-07-29 13:16:30 +08:00
|
|
|
try:
|
|
|
|
|
self.CreatConnect()
|
|
|
|
|
log.log_message(logging.INFO, Constant.str_tcp_reconnect)
|
|
|
|
|
except OSError as e1:
|
|
|
|
|
if e1.errno == 10056:
|
|
|
|
|
self.client_socket.close()
|
2025-09-10 09:16:57 +08:00
|
|
|
print("Error: 机械臂控制程序中TCPClient is not connected_1")
|
2025-07-29 13:16:30 +08:00
|
|
|
log.log_message(logging.ERROR,Constant.str_tcp_connect_error)
|
|
|
|
|
except Exception as e2:
|
|
|
|
|
print(e2)
|
|
|
|
|
|
|
|
|
|
def close(self):
|
|
|
|
|
self.thread_signal = False
|
|
|
|
|
self.client_socket.close()
|
|
|
|
|
|
|
|
|
|
def send_Command(self):
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
def send_Status(self):
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|