Plaster

common-lisp
(defun establish-tcp-listen (port) "Creates a listening TCP connection and returns the object for use in multiple functions" (let ((connection (usocket:socket-listen *IP* port :reuse-address t))) connection)) (defun maintain-connection-input () "Creates a contantly listening server for the device to connect to, on *tcp-port-input*, this function also sets the value of *remote-peer-ip* for use with (create-output-connection)" (let ((socket (establish-tcp-listen *tcp-port-input*))) (unwind-protect (loop (let* ((accepted (usocket:socket-accept socket))) (format *standard-output* "Remote PEER ~A" (usocket:get-peer-name accepted)) (if (null *REMOTE-PEER-IP*) (setf *REMOTE-PEER-IP* (usocket:get-peer-name accepted))) (let ((stream (usocket:socket-stream (usocket:wait-for-input accepted)))) (when stream (push-q *input-commands-queue* (json:decode-json stream)))))) (usocket:socket-close socket)))) (defun create-output-connection () "Creates a valid connected socket and sets *REMOTE-SERVER-CONNECTION-STREAM* to it. Uses the value of *remote-peer-ip* which is set by (maintain-connection-input) if this value has not been set, this function will just loop until it is eventually set. The value of *remote-server-connection-stream* being set to a valid socket is vital for the operation of the program " (if (null *remote-peer-ip*) (progn (format *standard-output* "PEER-IP IS NIL. TRYING AGAIN IN 1 SECOND~%") (sleep 1) (create-output-connection)) (handler-case (unwind-protect (let ((socket (socket-connect *remote-peer-ip* *tcp-port-output* :protocol :stream ))) (setf *REMOTE-SERVER-CONNECTION-STREAM* socket)) (when *REMOTE-SERVER-CONNECTION-STREAM* (usocket:socket-close *REMOTE-SERVER-CONNECTION-STREAM*))) (USOCKET:CONNECTION-REFUSED-ERROR (condition) (format *standard-output* "CONNECTION REFUSED ~A~% RETRYING IN 1 SECOND~%" condition) (sleep 1) (create-output-connection)))))