# Each processed response will be returned on a FIFO named pipe at the location "/tmp/response_$request_id" so that actions can be processed asynchronously
# If the response pipe does not exist when the data is done processing the response will not be sent at all, so the client must ensure that the response pipe exists when the JSON object is sent to the server!
# The response ID can be any unique value, an example ID generation statement in Bash is request_id="retrodeck_request_$(date +%s)_$$"
# The server can be started, stopped or have its running status checked by calling the script like this: retrodeck_api start
localbuffer=""# Buffer to accumulate lines from the request pipe, needed for multi-line JSON requests
while true;do
ifIFS=read -r line;then# Read one line from the request pipe
buffer+="$line"$'\n'# Append the line (plus a newline) to the buffer
ifecho"$buffer"| jq empty 2>/dev/null;then# Check if the accumulated buffer is valid JSON
log d "Received complete request:"
log d "$buffer"
process_request "$buffer"&# Process the complete JSON request asynchronously
buffer=""# Clear the buffer for the next request.
fi
fi
done < "$REQUEST_PIPE"
}
process_request(){
# This is the main API function loop. From the passed JSON object $1, it will check for values in the "action", "request_id" (which are always required fields) as well as any function-specific data.
# The "request_id" is also used in the construction of the response named_pipe the requesting client needs to create. The response named pipe will always be /tmp/response_$request_id and will be cleaned up by the server once the response has been sent.
# USAGE: process_request "$JSON_OBJECT"
localjson_input="$1"
local action
local request_id
# Validate JSON format
if ! echo"$json_input"| jq empty 2>/dev/null;then
echo"Error: Invalid JSON format" >&2
return1
fi
# Extract the action and parameters from the JSON input
# This is a dummy function used for API testing only. All it does is sleep for the amount of seconds provided in the "data" field of the received JSON object
localinput="$1"
sleep "$1"# Dummy implementation for demonstration