Files
2026-03-17 14:30:01 -06:00

107 lines
3.4 KiB
Python

"""
Copyright (C) 2023 Adobe.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
# file: network/client.py
# brief: Client requests
# author Adobe - 3D & Immersive
# copyright 2023 Adobe Inc. All rights reserved.
import traceback
import socket
import threading
import json
from time import sleep
from ..utils import SUBSTANCE_Utils
from ..common import (
Code_Response,
SRE_HOST,
SRE_PORT,
CLIENT_THREAD_THROTTLE_MS,
CLIENT_BUFFER_SIZE
)
class SRE_Client():
def __init__(self):
self.next_thread_start = SUBSTANCE_Utils.get_current_time_in_ms() + CLIENT_THREAD_THROTTLE_MS
def async_request(self, endpoint, op, data={}):
_throttle_ms = 0
_current_ms = SUBSTANCE_Utils.get_current_time_in_ms()
if _current_ms > self.next_thread_start:
self.next_thread_start = _current_ms + CLIENT_THREAD_THROTTLE_MS
else:
_throttle_ms = self.next_thread_start - _current_ms
self.next_thread_start = self.next_thread_start + CLIENT_THREAD_THROTTLE_MS
threading.Thread(
target=self._process_threaded_request,
args=(endpoint, op, data, _throttle_ms/1000)).start()
def _process_threaded_request(self, endpoint, op, data={}, throttle=0):
if throttle > 0:
sleep(throttle)
_result = self.sync_request(endpoint, op, data=data)
if _result[0] is not Code_Response.success:
SUBSTANCE_Utils.log_data("ERROR", "[{}] Threaded request fail: {}".format(_result, endpoint))
def sync_request(
self,
endpoint,
op,
data={}):
try:
_client_socket = socket.socket()
_client_socket.connect((SRE_HOST, SRE_PORT))
_message = {
"type": endpoint,
"op": op,
"data": data
}
_data = json.dumps(_message)
_client_socket.send(_data.encode())
_raw_response = b""
while True:
_buffer = _client_socket.recv(CLIENT_BUFFER_SIZE)
_raw_response += _buffer
if len(_buffer) < CLIENT_BUFFER_SIZE:
break
_response = _raw_response.decode()
_client_socket.close()
return (Code_Response.success, _response)
except ConnectionRefusedError:
SUBSTANCE_Utils.log_data("ERROR", "Exception - Refused connection error")
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
return (Code_Response.client_connection_refused_error, endpoint)
except Exception:
SUBSTANCE_Utils.log_data("ERROR", "Exception - Client connection error: {}".format(endpoint))
SUBSTANCE_Utils.log_traceback(traceback.format_exc())
return (Code_Response.client_connection_error, endpoint)