ai_project_v1/grpc_util/grpc_sam3/sam3_grpc_client.py

73 lines
2.3 KiB
Python
Raw Normal View History

2026-01-05 16:29:39 +08:00
import grpc
import time
2026-03-05 14:51:08 +08:00
from grpc_util.grpc_sam3 import grpc_sam3_img_pb2_grpc, grpc_sam3_img_pb2
2026-01-05 16:29:39 +08:00
def check_server_status(channel):
try:
2026-03-05 14:51:08 +08:00
health_stub = grpc_sam3_img_pb2_grpc.HealthCheckStub(channel)
response = health_stub.Check(grpc_sam3_img_pb2.HealthCheckRequest(service="TaskService"))
return response.status == grpc_sam3_img_pb2.HealthCheckResponse.ServingStatus.SERVING
2026-01-05 16:29:39 +08:00
except grpc.RpcError as e:
print(f"Health check failed: {e}")
return False
def check_grpc_request(max_retries=3, delay=5):
channel = None
retries = 0
while retries < max_retries:
try:
# 创建通道
2026-03-05 14:51:08 +08:00
channel = grpc.insecure_channel('192.168.110.187:9999')
2026-01-05 16:29:39 +08:00
# 检查服务器状态
if not check_server_status(channel):
raise Exception("Server is not healthy")
2026-03-05 14:51:08 +08:00
stub = grpc_sam3_img_pb2_grpc.TaskServiceStub(channel)
2026-01-05 16:29:39 +08:00
# 创建请求消息
2026-03-05 14:51:08 +08:00
request = grpc_sam3_img_pb2.TaskRequest(
task_id="d6118954-a170-4e1c-84bd-ddbd3114b354111",
2026-01-05 16:29:39 +08:00
sn="8UUXN6S00A0CK7",
2026-03-05 14:51:08 +08:00
content_body=grpc_sam3_img_pb2.ContentBody(
img_url="demo/03.png",
prompt="cat",
confidence=0.5,
mqtt_ip="47.108.62.6",
mqtt_port=12503,
mqtt_topic="thing/product/ai/events"
2026-01-05 16:29:39 +08:00
)
)
# 调用远程方法
response = stub.ProcessTask(request)
print(f"Response: task_id={response.task_id}, success={response.success}, message={response.message}")
return True
except grpc.RpcError as e:
retries += 1
print(f"RPC error occurred (attempt {retries}/{max_retries}): {e}")
if retries < max_retries:
print(f"Retrying in {delay} seconds...")
time.sleep(delay)
except Exception as e:
print(f"Error occurred: {e}")
retries += 1
if retries < max_retries:
print(f"Retrying in {delay} seconds...")
time.sleep(delay)
finally:
if channel:
channel.close()
print("All retry attempts failed")
return False
if __name__ == '__main__':
2026-03-05 14:51:08 +08:00
check_grpc_request()